Exciting News! Flipper Code is now WePlugins! Same commitment to excellence, brand new identity.

How to use post_thumbnail_id filter in WordPress

Sandeep Kumar Mishra
Sandeep Kumar Mishra
March 23, 2023
5 minutes read

post_thumbnail_id filter

Filters the post thumbnail ID.

apply_filters( 'post_thumbnail_id', int|false $thumbnail_id, int|WP_Post|null $post )

Description

This is a filter hook that filters the post thumbnail ID. It consists of two parameters: one is the thumbnail ID or false if the post does not exist, and the second is the Post ID or WP_Post object.

It is used in get_post_thumbnail_id(), which retrieves the thumbnail ID.

Parameters

  • $thumbnail_id : (int|false) Post thumbnail ID or false if the post does not exist.
  • $post : (int|WP_Post|null) Post ID or WP_Post object. Default is global $post.

Live Example 1: Custom Thumbnail ID

This example shows how to modify the post thumbnail ID to a custom ID if certain conditions are met.

    add_filter('weplugins_post_thumbnail_id', 'weplugins_custom_thumbnail_id', 10, 2);
    function weplugins_custom_thumbnail_id($thumbnail_id, $post) {
        if($post->post_type == 'custom_post_type') {
            return 123; // Custom thumbnail ID
        }
        return $thumbnail_id;
    }
    

Live Example 2: Default Thumbnail for Missing Posts

Use this example to set a default thumbnail ID when the post does not have one.

    add_filter('weplugins_post_thumbnail_id', 'weplugins_default_thumbnail_id', 10, 2);
    function weplugins_default_thumbnail_id($thumbnail_id, $post) {
        return $thumbnail_id ? $thumbnail_id : 456; // Default thumbnail ID
    }
    

Live Example 3: Alter Thumbnail ID Based on Post Author

In this example, we adjust the thumbnail ID based on the author’s ID.

    add_filter('weplugins_post_thumbnail_id', 'weplugins_author_based_thumbnail_id', 10, 2);
    function weplugins_author_based_thumbnail_id($thumbnail_id, $post) {
        if($post->post_author == 1) {
            return 789; // Thumbnail ID for author with ID 1
        }
        return $thumbnail_id;
    }
    

Access Premium WordPress Plugins

Contact Us

If you need any customization or have queries, feel free to Contact Us.

Sandeep Kumar Mishra

Sandeep Kumar Mishra

Sandeep Kumar Mishra writes about WordPress and Artificial Intelligence, offering tips and guides to help you master your website and stay updated with the latest tech trends.

Explore the latest in WordPress

Trying to stay on top of it all? Get the best tools, resources and inspiration sent to your inbox every Wednesday.