How to add snippet to one blog only in multisite

Hi, in a multisite I need to install a certain Google codesnippet into the header of every page of only one of the blogs. And another snippet into the header of only one specific page of the same blog. How can I achieve that?

  • Kasia Swiderska
    • Support nomad

    Hello Chris,

    You should be able to do that with code snippet used as Must Use Plugin. Somethings like that:

    <?php
    /* Describe what the code snippet does so you can remember later on */
    add_action('wp_head', 'your_function_name');
    function your_function_name(){

    $blogID = 'Your Blog ID';
    $pageID = 'Your Page ID';

    $blog_id = get_current_blog_id();
    $page_id = get_the_ID();

    if ($blog_id == $blogID ) {

    ?>

    // PASTE HEADER CODE HERE FOR ALL BLOG PAGES

    <?php

    }

    if ($blog_id == $blogID && $page_id == $pageID) {

    ?>

    // PASTE HEADER CODE HERE for only One PAGE

    <?php

    }

    };

    I’ve used functions:

    https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head

    https://codex.wordpress.org/Function_Reference/get_current_blog_id (to get the current blog ID)

    https://developer.wordpress.org/reference/functions/get_the_id/ (to get the page ID)

    and Must Use plugins https://codex.wordpress.org/Must_Use_Plugins

    Let me know if you have more questions

    kind regards,

    Kasia

  • Chris
    • Site Builder, Child of Zeus

    Hi, thanks for your reply. I inserted your code to mu-plugins. However, something went wrong because I now get a ‘white screen’. I probably inserted the script into your code at the wrong position (before the ‘<?php’ tag (but same result if within php tag) ; see:

    <?php

    /* Adds a code snippet to the header of all pages of one blog within a multisite */

    add_action(‘wp_head’, ‘your_function_name’:wink:;

    function your_function_name(){

    $blogID = ‘8’;

    $pageID = ‘Your Page ID’;

    $blog_id = get_current_blog_id();

    $page_id = get_the_ID();

    if ($blog_id == $blogID ) {

    ?>

    // PASTE HEADER CODE HERE FOR ALL BLOG PAGES

    <!– Global site tag (gtag.js) – Google Ads: 855663229 –>

    <script async src=”https://www.googletagmanager.com/gtag/js?id=AW-855663229″></script>

    <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag(‘js’, new Date()); gtag(‘config’, ‘AW-855663229’:wink:; </script>

    <?php

    }

    if ($blog_id == $blogID && $page_id == $pageID) {

    ?>

    // PASTE HEADER CODE HERE for only One PAGE

    <?php

    }

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.