Get template part vs locate template function

I’m in single.php where I’m trying to get related-posts.php template. The problem is that when using get template part the related-posts.php isn’t getting custom taxonomy name from single.php in wp_Query.

The solution is getting the wp post terms once again in related-posts.php in order to use get_template_part. But technically it shouldn’t be required since parent (single.php) is already having it.

But when I use locate template function it works fine. I feel that this method would be slower than get_template_part. What should I do?

1 Answer
1

First of all note that get_template_part internally uses locate_template, so your feeling that the latter is slower is wrong.

If you look at the code, get_template_part is little more than a wrapper for locate_template, so if one work and the other not, there are 2 possibilities:

  • you are using get_template_part wrong
  • there’s some hook on "get_template_part_{$slug}" action that prevent it works

However, if locate_template works, use it: it’s not slower, to be honest it can be pretty faster if there are functions hooked on "get_template_part_{$slug}" that slow down execution.

Leave a Comment