Calling WordPress get_template_part from inside a shortcode function renders template first

試著忘記壹切 提交于 2019-12-05 02:37:22

You may try this, it may solve your problem because get_template_part basically reacts like PHP's require, it doesn't return but echos the content immediately where it's been called.

add_shortcode('donation-posts', 'fnDonatePosts');   
function fnDonatePosts($attr, $content)
{        
    ob_start();  
    get_template_part('donation', 'posts');  
    $ret = ob_get_contents();  
    ob_end_clean();  
    return $ret;    
}

Here is a more dynamic version where you can pass the path to the template.

function template_part( $atts, $content = null ){
   $tp_atts = shortcode_atts(array( 
      'path' =>  null,
   ), $atts);         
   ob_start();  
   get_template_part($tp_atts['path']);  
   $ret = ob_get_contents();  
   ob_end_clean();  
   return $ret;    
}
add_shortcode('template_part', 'template_part');  

And the shortcode:

[template_part path="includes/social-sharing"]

Minimal version of the accepted answer:

function my_template_part_shortcode() {
    ob_start();
    get_template_part( 'my_template' );
    return ob_get_clean();
}
add_shortcode( 'my_template_part', 'my_template_part_shortcode' );

where my-template.php is the file you'd like to include.

get_template_part() didn't work for me when using it in functions.php. I used locate_template() inside the ob_start and clean instead. For example:

function full_petition_shortcode( $attr ) {
    ob_start();
    locate_template( 'petition.php', TRUE, TRUE );

    return ob_get_clean();
}
add_shortcode( 'full-petition', 'full_petition_shortcode' );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!