Search

Guide to Finding Appropriate Hooks in a WordPress Theme or Plugin

Listen to this article

search-filters-actions-wordpressHow often do you find yourself searching for an action or filter hook? It’s pretty much every time you have to make a change. May it be when creating an add-on plugin or a child theme. Wouldn’t you agree? For example, say you have to change the featured image of a post dynamically. How would you go about it?

What I’ll do, is I’ll set a definite goal. Then we’ll go about and track down the exact hooks needed to resolve our issue.

[space]

Example Scenario: Display a Specific Featured Image for a Post

So here’s what we’ll try doing. We’ll try displaying a specific image, with say id 4, for post id 27. (Just an example, your ids could differ if you were testing this out). Here are some additional details. Say the current id of the featured image for the post is 12.

Quick Tip: How to find the id of an image/attachment?

  • Go to the Media Library
  • Select any Image
  • Check the URL. It should be something as the following: http://example.com/wp-admin/post.php?post=4&action=edit
  • The value associated with that post attribute is attachment id.

(Let’s make this fun)

You have one additional constraint. You can’t make any changes in the database to change the featured image.

So the only option you have (and you know it) is to find a suitable filter hook to replace the featured image.

Let’s evaluate how featured images are displayed for posts.

The featured image of a post is displayed on the frontend using either the get_the_post_thumbnail or the_post_thumbnail functions. These functions locate the post’s featured image id, and then return the HTML code to display the image.

The mapping between the featured image and the post is stored in the table wp_postmeta. The key _thumbnail_id is used to store the mapping. The value associated with this key is the attachment id of corresponding image.

In our case, this would mean, if we took a look at the wp_options table, and searched for _thumbnail_id key for post 27, then the value of the key would be set to 12.

All good so far? Moving on.

[space]

Seek and ye shall find! How to Track Down the *Perfect* Hook

We now know WordPress will display the image by fetching the value set for _thumbnail_id. Hence we will need to alter this value obtained before the featured image is displayed.

The best bet we have is to find a suitable filter hook either in the get_the_post_thumbnail or the_post_thumbnail function.

For the sake of this tutorial, we’ll be evaluating the get_the_post_thumbnail function (the_post_thumbnail function is merely a wrapper over the get_the_post_thumbnail function. The difference is that the_post_thumbnail echoes the output returned by get_the_post_thumbnail).

The get_the_post_thumbnail function is defined in wp-includes/post-thumbnail-template.php.

[space]

Step 1: Check for a Filter before a Value is returned

Open the post-thumbnail-template.php file and find the function definition for get_the_post_thumbnail. You will notice, this function calls the get_post_thumbnail_id function to get the thumbnail id.

get_post_thumbnail_id( $post_id );

The output of this function is assigned to variable $post_thumbnail_id.

If there was filter before the return value, then writing code on that filter would work for us. But alas! there is no such filter. So what’s next? We have to take a look at the nested function inside the current function. In our case this function would be the get_post_thumbnail_id function.

[space]

Step 2: Check for a Filter in the Nested function

Locate the get_post_thumbnail_id function. It is defined in the same file. Check the return value of the function. The function returns the result of get_post_meta function.

return get_post_meta( $post_id, '_thumbnail_id', true );

But you’re faced with the same problem here. There isn’t a filter before the return value, and hence it can’t be changed.

[space]
“PATIENCE YOU MUST HAVE my young padawan”
[space]

I’m sure you know what we have to do next.

We need to dig into the get_post_meta function. This function searches for the value of _thumbnail_id in the database for $post_id. We need to get a filter here.

Lets get into that function right away.

[space]

Step 3: Keep digging deeper!

The get_post_meta function is defined in wp-includes/post.php and it contains only one line:

return get_metadata('post', $post_id, $key, $single);

But no filter there which means we will have to dig into the function get_metadata.

The get_metadata function is defined in wp-includes/meta.php. This function has has just what we need. Awesome!

$check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single );

Writing our code on this filter will do the job. We’ll return the image id we need (12). Let’s go for it.

In our case {$meta_type} is post since we are dealing with post data. Therefore, our code should be as follows:

add_filter( 'get_post_metadata', 'wdm_change_featured_image', 10, 4 );
/*
* Sets featured image dynamically
*
* @param int $featured_image_id  Image/Attachment ID. Default value is null
* @param int $post_id  Post id of the post
* @param string $meta_key  Meta key for which value to be set
* @param string $single Meta value, or an array of values.
* @return mixed Returns the featured image id
*/
function wdm_change_featured_image( $feature_image_id = null, $post_id, $meta_key, $single ) {
    //we have to return 12 if post id is 27
    if ( $post_id == 27 && meta_key == '_thumbnail_id' ) {
      return 12;
    }
    return $feature_image_id;
}

This code can be added in functions.php of your theme or in a custom plugin. Either way you’re set.

[space]

If you’re lucky, the filter you’re looking for will be in the first place you look. If not, I hope the way I tracked the filter will help you overcome a few hurdles. And be sure to share helpful tips for fellow developers in the comment section below!

[space]
“Always pass on what you have learned.”

Sumit Pore

Sumit Pore

2 Responses

  1. Thanks, this was helpful!

    BTW, you appear to have a typo (wp_postmeta in first paragraph, wp_options in second):
    “The mapping between the featured image and the post is stored in the table wp_postmeta. The key _thumbnail_id is used to store the mapping. The value associated with this key is the attachment id of corresponding image.

    In our case, this would mean, if we took a look at the wp_options table, and searched for _thumbnail_id key for post 27, then the value of the key would be set to 12.”

Leave a Reply

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

Get The Latest Updates

Subscribe to our Newsletter

A key to unlock the world of open-source. We promise not to spam your inbox.

Suggested Reads

WordPress Development

Custom WordPress Solutions, for You

LearnDash Development

Custom LearnDash Solutions, for You

WooCommerce Development

Custom WooCommerce Solutions, for You

WordPress Plugins

Scale your WordPress Business

WooCommerce Plugins

Scale your WooCommerce Business

LearnDash Plugins

Scale your LearnDash Business

Label

Title

Subtext

Label

Title

Subtext

Join our 55,000+ Subscribers

    The Wisdm Digest delivers all the latest news, and resources from the world of open-source businesses to your inbox.

    Suggested Reads