Using WordPress ‘post_thumbnail_size’ PHP filter

post_thumbnail_size is a WordPress PHP filter that allows you to modify the size of a post thumbnail.

Usage

add_filter( 'post_thumbnail_size', 'your_function_name', 10, 2 );
function your_function_name( $size, $post_id ) {
    // your custom code here
    return $size;
}

Parameters

  • $size (string|int[]): The requested image size, can be any registered image size name or an array of width and height values in pixels (in that order).
  • $post_id (int): The post ID for which the thumbnail is being filtered.

More information

See WordPress Developer Resources: https://developer.wordpress.org/reference/hooks/post_thumbnail_size/

Examples

Set a custom thumbnail size for a specific post

This code sets the thumbnail size to 300×200 pixels for the post with ID 42.

add_filter( 'post_thumbnail_size', 'change_thumbnail_size_for_specific_post', 10, 2 );

function change_thumbnail_size_for_specific_post( $size, $post_id ) {
    if ( $post_id == 42 ) {
        $size = array( 300, 200 );
    }
    return $size;
}

Set a different thumbnail size for posts in a specific category

This code sets the thumbnail size to ‘medium’ for posts in the ‘Featured’ category.

add_filter( 'post_thumbnail_size', 'change_thumbnail_size_for_featured_category', 10, 2 );

function change_thumbnail_size_for_featured_category( $size, $post_id ) {
    if ( has_category( 'Featured', $post_id ) ) {
        $size = 'medium';
    }
    return $size;
}

Set a custom thumbnail size for all posts

This code sets the thumbnail size to 500×300 pixels for all posts.

add_filter( 'post_thumbnail_size', 'change_thumbnail_size_for_all_posts', 10, 2 );

function change_thumbnail_size_for_all_posts( $size, $post_id ) {
    $size = array( 500, 300 );
    return $size;
}

Set a square thumbnail size for posts with a specific tag

This code sets the thumbnail size to 200×200 pixels for posts with the ‘New’ tag.

add_filter( 'post_thumbnail_size', 'change_thumbnail_size_for_new_tag', 10, 2 );

function change_thumbnail_size_for_new_tag( $size, $post_id ) {
    if ( has_tag( 'New', $post_id ) ) {
        $size = array( 200, 200 );
    }
    return $size;
}

Set a custom thumbnail size based on the current user’s role

This code sets the thumbnail size to ‘large’ for administrators and ‘medium’ for other users.

add_filter( 'post_thumbnail_size', 'change_thumbnail_size_based_on_user_role', 10, 2 );
function change_thumbnail_size_based_on_user_role( $size, $post_id ) {
    if ( current_user_can( 'manage_options' ) ) {
        $size = 'large';
    } else {
        $size = 'medium';
    }
    return $size;
}