2

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.

  • 2
    do you really call return before `restore_current_blog()` in your shortcode? (it sounds like it, reading your code comments). Returning the html should be the last line instead. – birgire Mar 16 '17 at 23:44
  • 1
    @birgire I think that is the answer to the OP's question. You should post it. – Cave Johnson Mar 17 '17 at 02:22

1 Answers1

1

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.

birgire
  • 11,258
  • 1
  • 31
  • 54
  • Perfect thanks, didn't notice that! I've switched to blog just to fetch the variables. –  Mar 24 '17 at 11:54