Site icon Dhanendran's Blog

Using get_template_part within Shortcode

The get_template_part is a one of the most useful function for the theme developers. It prints/includes the template content inside another template. It is used as an alternative to include or require.

We can make use of this function within the WordPress shortcode to include or display the output. But there are few things to note on this approach.

  1. Shortcode callback functions expect to return the data/results.
  2. get_template_part function is always executes the file and generates the output. i.e., it prints the output.

So when it is used directly you can notice that the generated output is displayed before the post content but not replaced inline.

Don’t very we have the trick to fix this 🙂

PHP’s Output Buffering is the perfect solution for this.

Yes it is…

Create a buffer with ob_start() in your shortcode callback function before calling get_template_part() and catch the output with ob_get_clean() like below.

function my_shortcode_callback( $attr ) {
    ob_start();
    get_template_part();

    return ob_get_clean();
}
add_shortcode( 'my_shortcode', 'my_shortcode_callback' );

 

This approach can be used with other functions as well which will generate output like include and require.

Exit mobile version