Search code examples
phpwordpresscustom-post-typeshortcodemultisite

switch_to_blog() within WordPress shortcode


Using a WordPress multisite network, I need to access custom post types from our main site from within a shortcode.

For example, our main site (ID 1) is where the custom post types (Case Studies) are stored. In functions.php I have the following:

//[casestudy]
add_shortcode( 'casestudy', 'casestudy_shortcode' );

function casestudy_shortcode( $atts ) {
    $a = shortcode_atts( array(
        'id' => ''
    ), $atts );

    switch_to_blog(1);

    //Get fields from custom post type with Advanced Custom Fields Pro
    //and return HTML output with them

    restore_current_blog();
}

Then call the shortcode with [casestudy id="123"] where the ID is the post ID of the case study.

The problem is, doing this returns the Case Study HTML fine but breaks some features of the page and also populates the 'recent posts' widget with blog posts of the main site.

Any ideas on what's going wrong? Thanks.


Solution

  • Adding my comment as an answer:

    Reading the OP code comments, it looks like restore_current_blog() is never called, because the HTML is returned before calling it.

    Make sure that the return part is the last line in there.