Using WordPress ‘post_thumbnail_id’ PHP filter

The post_thumbnail_id WordPress PHP filter allows you to modify the ID of a post thumbnail before it’s displayed on your website.

Usage

add_filter( 'post_thumbnail_id', 'your_custom_function', 10, 2 );

function your_custom_function( $thumbnail_id, $post ) {
    // your custom code here

    return $thumbnail_id;
}

Parameters

  • $thumbnail_id int|false – The ID of the post thumbnail, or false if the post does not exist.
  • $post int|WP_Post|null – The Post ID or WP_Post object. The default is the global $post variable.

More information

See WordPress Developer Resources: post_thumbnail_id

Examples

Change Thumbnail ID for Specific Post

Replace the thumbnail ID for a specific post with another image ID.

function replace_thumbnail_id( $thumbnail_id, $post ) {
    if ( $post->ID == 42 ) {
        $thumbnail_id = 123; // Replace with the new image ID
    }
    return $thumbnail_id;
}
add_filter( 'post_thumbnail_id', 'replace_thumbnail_id', 10, 2 );

Show Default Thumbnail for Posts Without Thumbnail

Show a default thumbnail for posts that don’t have a thumbnail set.

function set_default_thumbnail( $thumbnail_id, $post ) {
    if ( !$thumbnail_id ) {
        $thumbnail_id = 456; // Set the default thumbnail ID
    }
    return $thumbnail_id;
}
add_filter( 'post_thumbnail_id', 'set_default_thumbnail', 10, 2 );

Swap Thumbnail ID for Even and Odd Posts

Display different thumbnails for even and odd post IDs.

function swap_even_odd_thumbnail( $thumbnail_id, $post ) {
    if ( $post->ID % 2 == 0 ) {
        $thumbnail_id = 789; // Thumbnail ID for even post IDs
    } else {
        $thumbnail_id = 101112; // Thumbnail ID for odd post IDs
    }
    return $thumbnail_id;
}
add_filter( 'post_thumbnail_id', 'swap_even_odd_thumbnail', 10, 2 );

Display Random Thumbnail from a Pool

Choose a random thumbnail from a predefined pool of image IDs.

function random_thumbnail_from_pool( $thumbnail_id, $post ) {
    $pool = array( 131415, 161718, 192021 ); // Array of image IDs
    $thumbnail_id = $pool[array_rand( $pool )];
    return $thumbnail_id;
}
add_filter( 'post_thumbnail_id', 'random_thumbnail_from_pool', 10, 2 );

Remove Thumbnails from a Specific Category

Remove post thumbnails for a specific category.

function remove_thumbnail_for_category( $thumbnail_id, $post ) {
    if ( in_category( 'no-thumbnails', $post ) ) {
        $thumbnail_id = false; // Remove the thumbnail
    }
    return $thumbnail_id;
}
add_filter( 'post_thumbnail_id', 'remove_thumbnail_for_category', 10, 2 );