Using get_template_part within Shortcodes

The get_template_part function is one of the most useful things available to WordPress theme developers. Although mostly used in themes for public, get_template_part is often used in custom WordPress websites as an alternative to the PHP include or require.

When using get_template_part with the Shortcode API, there are two things you should always keep in mind:

  • get_template_part executes .php files which (most likely) generates output
  • shortcode callback functions are expected to return a string and not generate any output

So when calling get_template_part within a shortcode callback function, you’ll see that all the output generated by get_template_part is output before the post content, and not replaced inline.

The solution is to use PHP’s output buffering. Create a buffer in your shortcode callback before running get_template_part, clear the buffer and return the content right after. Here’s a quick example with an ads shortcode, which can insert your theme’s ads.php file contents anywhere within a post or page:

function my_ads_shortcode( $attr ) {
    ob_start();
    get_template_part( 'ads' );
    return ob_get_clean();
}
add_shortcode( 'ads', 'my_ads_shortcode' );

The ob_get_clean() function stops buffering and returns whatever was output to the buffer after ob_start(). The same approach could be used with other functions and statement that generate output, such as include and require.

About the author

Konstantin Kovshenin

WordPress Core Contributor, ex-Automattician, public speaker and consultant, enjoying life in Moscow. I blog about tech, WordPress and DevOps.

3 comments