Overide get_template_part( ‘partials/post’, ‘sidebar’ ); with a plugin

TL;DR: Use a child theme instead 🙂


If we dig into the code for get_template_part(), there’s an action there – get_template_part_{$slug} – which we could hook into.

Digging a bit further, get_template_part() calls locate_template(), which calls load_template(). Unfortunately, there’s nothing in either of these functions that seems to be pluggable, so we can’t hook in and change anything (with the exception of being able to set variables through the call to extract() in load_template()…. but we can’t override the template file being called so it’s not very useful anyway!)

So, it looks like your only option to catch this is by running code on the get_template_part_partials/post action. The problem is, this won’t allow you to filter the template called – it’ll just allow you to run some code when the template is called. If all you want to do is add some output above the templated code then this will suit you perfectly, but I doubt that’s all you want to do!

The way around all this is to use a child theme.

You said you wanted to put your code into a plugin in order to respect the original theme developer. Firstly, that respect is awesome – many developers wouldn’t care less so I commend you for that!

However, is a plugin the best choice? Plugins are generally used to add modular functionality to a site, not to change the look and feel of it. That’s the domain of themes.

You can in fact create a child theme which will let you modify the theme the site uses without making any changes to the parent theme. You should be able to apply all the changes you’ve already made here, plus you have the bonus that get_template_part() will automatically use a file within your child theme if it exists, before falling back to the parent theme.

Leave a Comment