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
.
Great Idea, Thank you :)
Glad you found it useful :)
I think this is the next level of get_template_part usage. I love get_template_part, it is like magic, it help me to work on WooThemes, when I have no time to digg around the code more.