0

I wanted to create a Menu component in my site that shows links to the different sites in my network (WordPress Multisite).

My solution was to create a site_option using CMB2. Each site will fill that up with the necessary values which then will be used for the menu to be displayed on the theme's header.php. However, I am only getting the main/default site's site_option data despite using switch_to_blog().

Here's the code:

$sites = wp_get_sites();
$current_site = get_current_blog_id();

foreach ($sites as $site) {
  $details = get_blog_details($site['blog_id']);
  $zSite = $details->blog_id;
  $mycolor = '';
  $mclass = '';

    if( $current_site == $zSite ) {
        $mclass = 'active';
    }

    switch_to_blog( $site[ 'blog_id' ] );
        $mycolor = myPrefix_get_option( 'test_colorpicker' ); //this is the get option function provided by CMB2. See the whole function here: https://github.com/WebDevStudios/CMB2-Snippet-Library/blob/master/options-and-settings-pages/theme-options-cmb.php
    restore_current_blog();

  printf( '<li role="presentation" class="%s"><a style="border-color:%s" href="%s">%s</a></li>', $mclass , $mycolor , 'http://'.$site['domain'].$site['path'], $details->blogname );
}

Can anyone help me out or maybe point me to a different solution to achieve my objective?

0

For those who stumble upon this in the future, this was actually answered by the CMB2 author himself, Michael Beckwith:

$sites = wp_get_sites();
$current_site = get_current_blog_id();

foreach ($sites as $site) {
  $details = get_blog_details($site['blog_id']);
  $zSite = $details->blog_id;
  $mycolor = '';
  $mclass = '';

    if( $current_site == $zSite ) {
        $mclass = 'active';
    }

    switch_to_blog( $site[ 'blog_id' ] );
        $mycolor = get_option( 'myprefix_options' ); // here's the updated code
        $mycolor = $mycolor['test_colorpicker']; // here's the updated code
    restore_current_blog();

  printf( '<li role="presentation" class="%s"><a style="border-color:%s" href="%s">%s</a></li>', $mclass , $mycolor , 'http://'.$site['domain'].$site['path'], $details->blogname );
}

According to Michael:

I believe the issue is stemming from the myprefix_admin() function, in the end. It's creating what's known as a singleton, which means only one instance of an object will exist at a given time. It's being run right away, and any time you do a call with myprefix_admin() afterwards will reference that first object. This includes inside foreach loops like what you're trying to do above.

...what we do is simply fetch the entire option, and then pluck out just the part we need, in this case the color picker value.

Thanks again CMB2's Michael Beckwith.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.