switch_to_blog()在WordPress短代码

问题描述:

使用WordPress多站点网络,我需要从短代码中访问我们主站点的自定义帖子类型。switch_to_blog()在WordPress短代码

例如,我们的主站点(ID 1)是存储自定义帖子类型(案例研究)的地方。在我的functions.php具备以下条件:

//[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(); 
} 

然后调用简码与[casestudy id="123"]其中ID为案例研究的帖子ID。

问题是,这样做会返回案例研究HTML的罚款,但会破坏页面的某些功能,并且还会在主站点的博客文章中填充“最近的帖子”窗口小部件。

关于发生什么问题的任何想法?谢谢。

+2

你真的会在你的短代码中'restore_current_blog()'之前调用return吗? (这听起来像是,阅读你的代码评论)。返回html应该是最后一行。 – birgire

+1

@birgire我认为这是OP问题的答案。你应该发布它。 –

添加我的评论作为一个答案:

读OP代码的注释,它看起来像restore_current_blog()不会被调用,因为HTML被调用前返回。

确保return部件是最后一行。

+0

完美的感谢,没有注意到!我已经切换到博客只是为了获取变量。 – wadclapp