Calling WordPress get_template_part from inside a shortcode function renders template first Calling WordPress get_template_part from inside a shortcode function renders template first wordpress wordpress

Calling WordPress get_template_part from inside a shortcode function renders template first


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.