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?
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.:
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 ofget_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.
get_template_part()
should be a correct choice. Because,Where, using custom function could –
out where the function was written, if needed to edit by someone else
any hook.
Advantage of using function
function( 'Number of related posts', 'Order', 'excluding / inclusion any posts')
etc.file_exists
), what takes some loading time, But functions loads much faster.That’s my opinion, others might have some better opinion.