get_template_part vs action hooks in themes

It seems to me both of these afford the opportunity for the end user to modify a theme without actually editing the themes files (via child themes).

My question is, is one method preferred over the other.

For example take a theme I am workig on now. I am trying to decide whether to go with template parts of hooks.

<?php get_template_part('before_sitecontainer' ); ?>
<div id="sitecontainer" class="sitecontainer" <?php //closed in footer ?>>

<?php get_template_part( 'before_topcontainer' ); ?>
<div id="topcontainer ">

    <?php get_template_part( 'before_topedge_navigation' ); ?>
    <?php get_template_part( 'topedge_navigation' ); ?>

    <?php get_template_part( 'before_site_header' ); ?>
    <?php get_template_part( 'site_header' ); ?>

    <?php get_template_part( 'before_second_navigation' ); ?>
    <?php get_template_part( 'second_navigation' ); ?>

    <?php get_template_part( 'after_second_navigation' ); ?>

</div><!-- end topcontainer div -->
<?php get_template_part( 'after_topcontainer' ); ?>

The above allows the user of the theme to replace any section of existing code by simply creating an appropiately named file in their child theme folder as well as adding new code before/after each pre existing section by the same method – the before/after template part files don’t exist in the parent theme at all and are there simply to allow them to insert code – and this method does not require they understand hooks/filters to accomplish this.

I could of course achieve the same using hooks and filters.

Is there an advantage to using hooks/filters instead? Bearing in mind the target audience that will be using this is decidely not code savvy. I can give them relatively basic instruction they can follow to use the template method but will almost surely confuse the devil out of them with hooks.

Or are there situations where one would be better than the other within the same theme?


I prefer hooks, since they are more flexible: you can hook into them from your theme’s functions.php file, but also from plugins. I try to put as much logic in plugins, so that the themes contain mostly layout stuff.

If you use an action hook, it is still possible to use get_template_part() in that hook handler. This gives you the best of both worlds. You could probably even create a default hook that calls get_template_part(), so that people who don’t have much experience with coding can add extra files, and others can remove this hook if they don’t want to.

Regarding performance: get_template_part() uses (in locate_template()) file_exists() one, two or four times (depending on how you call it). It appears file_exists() is very fast, and uses caching in PHP and maybe even in the OS. So that is probably not an issue.

Leave a Comment