Andreas Hecht September 21st, 2017

WordPress: Modern Theme Development With Action Hooks

Developing excellent WordPress themes is an actual challenge. But even the seemingly easy adjusting of existing themes can become pretty tough pretty fast. More and more developers use action hooks in their template files, as they help to keep a clear overview of the individual files, as well as the used functions. As there is very little information on working with action hooks out there, beginners and advanced users alike tend to run out of ideas quickly.

WordPress Action Hooks - an Introduction

To prevent that from happening to you, today, we'll look into action hooks and their advantages, to save you from these frustrations. If you want to open a WooCommerce shop, you may consider adjusting the popular Storefront theme to your needs. After opening the template file for the display of the start page, this is what you'll see: [caption id="attachment_84776" align="alignnone" width="1600"]Storefront WooCommerce Theme Welcome to the New and Clear World of Theming.[/caption] As you can see, there are no loops in this file. Other theme files of Storefront are designed like this, too. However, these files could be cleaned up even more: [caption id="attachment_84777" align="alignnone" width="1600"]WordPress Action Hooks Theme Datei Theming With Action Hooks Brought to the Boil. A Theme File Does Not Need to Contain More Than This.[/caption] Here, a single action hook takes care of the display of the star page's content.
<?php do_action( 'homepage' ); ?>

The Principle of the WordPress Action Hooks

The principle behind this is rather simple, and you already know it. WordPress already offers a couple of pre-defined hooks, which are commonly used. These include:
<?php
//Well Known Action Hooks: 

wp_head();

wp_footer();

the_content();

the_excerpt();

?>
The principle remains: functions are "hooked," and either executed or displayed. Your own, custom action hooks work the same way. But what exactly is the benefit of this type of development?

The Big Advantage of This Type of Theme Development

Now, you'll probably ask yourself what the benefit of this kind of development is. The answer is obvious. Aside from the clarity of the individual templates, there's another unbeatable benefit: For individually editing and adding new functions to an existing theme not a single theme file needs to be touched. The largest source of errors in custom theme files falls out completely. Modifications and custom functions can be added to the templates without having to change these files, using action hooks. They can "magically" appear right where you want them to. Allow me to summarize:
  • Clear structures
  • Absolute clarity
  • All functions in one place
  • No adjustment of single theme files required

How to Work With WordPress Action Hooks

Once you got the hang of it, working with action hooks is pretty simple. You define your own hook, program your function, and hook it. Creating an own hook is easy, the needed function is called do_action() However, before dealing with that, there are a few things to keep in mind.

Step 1: What You Should Pay Attention to

Clarity is the most important aspect. You should collect all template functions in one file. The functions.php, however, is not the right file for this job. Create an own file for this job, where you collect all functions that work on the display of the theme. The Storefront theme serves as a good example here, as you'll find all template functions in the folder /inc in the file storefront-template-functions.php. I recommend setting up a file like that too. A folder /inc is the right place for this file. However, you still need to tell WordPress about the existence of the file. One line of code in the functions.php makes sure that you file is loaded:
<?php require_once( get_stylesheet_directory(). '/inc/template-functions.php' ); ?>

Properly Document Your Code

A proper documentation of your code is crucial. Assume that other people will have to understand your code as well. Even if that isn't the case, after a year, you'll have problems finding your way around your own theme. A proper documentation provides a perfect overview at all times. I have solved this requirement like this: [caption id="attachment_84799" align="alignnone" width="1572"]So sollte eine gute Dokumentation aussehen. This is what a proper documentation should look like. Even the respective folder and the files are mentioned.[/caption]

Schritt 2: Defining a WordPress Action Hook

Define your hook within the brackets. For example, it could be called like this:
<?php do_action( 'startpage' ); ?>
If you need to divide words, use underscores instead of hyphens.
<?php do_action( 'startpage_loop' ); ?>
Now, place this hook in the theme file, wherever you want the function to be. You are not restricted here, and you get to use your action hooks almost anywhere. Before or after the content, before or after the heading, or the comments, for example. One example is Storefront's single.php: [caption id="attachment_84795" align="alignnone" width="2036"]Die single.php des Storefront-Theme veranschaulicht gut die Möglichkeiten der Hooks. The Storefront Theme's single.php is a Good Display of the Hook's Possibilities.[/caption]

Step 3: Working With the WordPress Action Hooks

Let's use the Storefront theme's start page as an example once more. You'll quickly realize that working with the hooks is pretty easy to grasp. Here's the start page's hook once again:
<?php do_action( 'homepage' ); ?>
Now, write your functions in the file you set up for that.
<?php

if ( ! function_exists( 'storefront_homepage_content' ) ) {
	/**
	 * Display homepage content
	 * Hooked into the `homepage` action in the homepage template
	 *
	 * @since  1.0.0
	 * @return  void
	 */
	function storefront_homepage_content() {
		while ( have_posts() ) {
			the_post();

			get_template_part( 'content', 'homepage' );

		} // end of the loop.
	}
}
Afterwards, your function is hooked and moved to the respective spot:
<?php

add_action( 'homepage', 'storefront_homepage_content', 10 );
Your function will now appear on the start page. First, write the action hook, then enter the function's name into the add_action() tag. It's that simple.

Step 4: One Hook, Many Functions

But, how does one place many functions with a single hook? The secret lies in the priorities. The lower the priority number, the higher up the function appears. Let's take a close look at the template: [caption id="attachment_84776" align="alignnone" width="1600"]Die template-homepage.php Datei von Storefront. The Storefront Theme's Homepage File.[/caption] Seven functions share one action hook. This is possible thanks to the priorities that appear behind each hooked function. Here in the example, this ranges from priority 10 to priority 70. These numbers determine the order of the executed functions. The ten appears at the top, the 70 at the very bottom. We distribute the priorities with the add_action() tag:
<?php

// The 10 is the priority
add_action( 'homepage', 'storefront_homepage_content', 10 );

Simply Sliding Functions in Between

Controlling the display of your file is that simple, and in the case of our example, you can even slide functions into the file wherever you want to. Just enter an "in-between priority" for your function.
<?php

add_action( 'homepage', 'your-own-function', 15 );
Now, due to the priority, your custom function is displayed between the Storefront homepage content and the product categories.

WooCommerce: Adding Share Buttons Without Template Modifications

Every WooCommerce shop owner wants to add the important share buttons on the display of an individual product. Thanks to the action hooks, this can be done within a few minutes. The respective file that we hook our share buttons into is share.php. [caption id="attachment_84797" align="alignnone" width="1800"]Die share.php mit dem Action Hook, indem wir unsere Share-buttons einhaken. The share.php With the Action Hook, Into Which We Hook Our Share Buttons.[/caption] Aside from the automatic integration of share buttons into the theme, many share button plugins give you the option to manually place the buttons. For the most part, this is done using a shortcode. The shortcode for the manual integration into the theme file looks like this:
<?php echo do_shortcode('[your-button-plugin]'); ?>
The function required for the integration into the view of a single product would look like this:
<?php
/**
 * Implementing Share Buttons on the Page of an Individual Product
 */
function share_for_woocommerce() {
    
    echo do_shortcode('[dein-button-plugin]');
}
add_action( 'woocommerce_share', 'share_for_woocommerce' );
As only a single function is hooked, defining priorities is not needed. The Result: [caption id="attachment_84798" align="alignnone" width="1600"]Share-Buttons an der richtigen Stelle ohne die Template-Datei angefasst zu haben. Perfekt! Share Buttons in the Right Spot Without Having Touched the Template File. Perfect![/caption]

Conclusion

WordPress action hooks are an excellent way to keep a theme's files clear and structured. A good code documentation with a thought-out folder and template structure provides massive advantages, as it allows other developers to find their way around quickly. Additionally, this modern theming is very user-friendly, as no files need to be altered to adjust a theme. Featured image by Thomas Park on Unsplash

Andreas Hecht

Andreas Hecht is a journalist and specialist for WordPress and WordPress Security. He roams the web since its inception. He has published an ebook on WordPress Security, which you might want to take a look at.

Leave a Reply

Your email address will not be published. Required fields are marked *