Programmeur
Programmeur

Reputation: 1531

WordPress Fallback Thumbnail image by size

I have more than one custom thumbnail size.

For example:

<?php
add_image_size( 'sizeOne', 300, 100 );
add_image_size( 'sizeTwo', 600, 200 );
?>

I show the thumbnail with the function:

<?php the_post_thumbnail( 'sizeOne' ); ?>

And, if the image does not exist (if I haven't set the custom thumbnail in Admin area), the fallback image will be default-thumbnail.png. This process is made by this code in functions.php:

<?php
function filter_post_thumbnail_html( $html ) {
    // If there is no post thumbnail,
    // Return a default image
    if ( '' == $html ) {
        return '<img src="' . get_template_directory_uri() . '/images/default-thumbnail.png" width="300" height="100" />';
    }
    // Else, return the post thumbnail
    return $html;
}
add_filter( 'post_thumbnail_html', 'filter_post_thumbnail_html' );
?>

The problem is that the fallback image is the same for all thumbnail sizes. As it's 300x100, it is perfect to sizeOne, but is too small for sizeTwo.

How can I "check" if the thumbnail asked is sizeOne or sizeTwo and then return the correct fallback image?

Ps: I know the other way to do this, but that's not what I want.

<?php 
    if ( has_post_thumbnail() ) {
        the_post_thumbnail( 'sizeOne' );
    } else {
?>
    <img src="<?php bloginfo('template_directory'); ?>/images/default-thumbnail.jpg" width="300" height="100" />
<?php 
} ?>

Upvotes: 0

Views: 353

Answers (1)

Jared
Jared

Reputation: 12524

You can use the additional parameters of the filter.

<?php
function filter_post_thumbnail_html( $html, $post_id, $post_thumbnail_id, $size ) {
    // If there is no post thumbnail,
    // Return a default image
    if ( '' == $html ) {
        if ( 'sizeTwo' == $size ) {
            return '<img src="' . get_template_directory_uri() . '/images/default-thumbnail2.png" width="600" height="200" />'; 
        } else {
            return '<img src="' . get_template_directory_uri() . '/images/default-thumbnail.png" width="300" height="100" />';
        }

    }
    // Else, return the post thumbnail
    return $html;
}
add_filter( 'post_thumbnail_html', 'filter_post_thumbnail_html', 10, 4 );

Upvotes: 1

Related Questions