[wp-trac] [WordPress Trac] #42688: Option to make get_template_part return instead of require

WordPress Trac noreply at wordpress.org
Fri Nov 24 10:02:10 UTC 2017


#42688: Option to make get_template_part return instead of require
-------------------------+-----------------------------
 Reporter:  mclaurent    |      Owner:
     Type:  enhancement  |     Status:  new
 Priority:  normal       |  Milestone:  Awaiting Review
Component:  Themes       |    Version:  4.9
 Severity:  normal       |   Keywords:
  Focuses:  template     |
-------------------------+-----------------------------
 Having the ability to have a template returned instead of required would
 be extremely helpful for building shortcodes using get_template_part to
 load reusable sections of code in the theme. Current work-arounds include
 output buffering and using locate_template, both of which have their own
 downsides.

 {{{
 #!php
 <?php
 function get_product_template($atts) {

     // the last boolean attribute would toggle between $echo = true or
 false.
     // Shortcodes should return output instead of outputting it directly.
     return get_template_part( 'product', $atts['type'], false );
 }
 add_shortcode('products', 'get_product_template');
 }}}


 The current work-around with output buffering looks something like this
 but it feels heavy for what it is meant to do.

 {{{
 #!php
 <?php
 function get_product_template($atts) {

     ob_start();

     get_template_part( 'product', $atts['type'], false );

     $ret = ob_get_contents();
     ob_end_clean();
     return $ret;
 }
 add_shortcode('products', 'get_product_template');
 }}}

 The alternative work-around is using locate_template however this does not
 check for fallback templates nor does it evaluate any PHP inside the
 template.

 {{{
 #!php
 <?php
 function get_product_template($atts) {

     $attribute = $atts[ 'type' ];
     return file_get_contents(locate_template( "product-{$atts}.php" ) );

 }
 add_shortcode('products', 'get_product_template');
 }}}

--
Ticket URL: <https://core.trac.wordpress.org/ticket/42688>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list