Template tags vs get_template_part() vs functions.php

When to use template tags and when to use get_template_part() and when to use function.php? I am confused at them.

For example, if I want to show related portfolios under single portfolio, I can create a template tag named show_related_portfolios().

In contrast, I can create a file named content-related-portfolios.php, and use it like get_template_part( 'content', 'related-portfolios' ).

Or I can create a function which fetches related portfolios in functions.php.

Is there any best practices for using them?

2 Answers
2

A template tag is just a function, so I can’t understand the difference from a function in functions.php and a template tag.

So the choiches are 2: function VS file.

The right choice depend case by case, and all things @shazzad pointed found me agree.

I prefer use file and get_template_part when the code need to contain a lot of html, because I don’t like having functions that open and close php tags or with large echo of html output.

In short I prefer file when the needed feature is all about presentation and prefer function when I need some computational work.

Sometimes I use both, e.g.:

if ( ! function_exists('show_related_portfolios') ) {

    function show_related_portfolios( $someargs = array() ) {
      $defaults = array( ... );
      $args = wp_parse_args( $someargs, $defaults );
      $related_q = new WP_query();
      if ( $related_q->have_posts() ) {
        while( $related_q->have_posts() ) { $related_q->the_post();
          // template for singular related portfolio
          get_template_part( 'content', 'related-portfolio' ); 
        }
      }
      wp_reset_postdata(); 
    }

}

in this way I can make use of function arguments, move the great part of php inside a function and template can be just html for the most part.

Using function also allow to use the feature as shortcode with very little work.

Note the if ( ! function_exists('show_related_portfolios') ) { statement: this prevent error if the function is already defined and in addition allow child themes to override the function completely. In addition, thanks to the use of get_template_part child themes can easily override the display of the singular item.

Note that is just a case, the one you used as example, but is impossible a general rule of what is better.

Leave a Comment