如何通过在Function.php中实现一些代码来使用默认图像作为特色图像

时间:2020-08-29 作者:Puneet Verma

我想使用默认图像作为所有这些帖子和页面的特色图像,其中没有任何从媒体选择的特色图像。我在中尝试了此代码function.php 但不起作用,

function filter_post_thumbnail( $html ) {
    if ( \'\' == $html ) {
        return \'<img src="https://upload.wikimedia.org/wikipedia/commons/f/f9/Google_Lens_-_new_logo.png" />\';
    }
    // Else, return the post thumbnail
    return $html;
}
add_filter( \'post_thumbnail_html\', \'filter_post_thumbnail\' );
通过在function.php 文件

1 个回复
最合适的回答,由SO网友:Rup 整理而成

To make your existing code work you\'ll also need to override has_post_thumbnail:

add_filter( \'has_post_thumbnail\', \'__return_true\' );

since your theme is probably guarding get_the_post_thumbnail() with has_post_thumbnail(), so that now needs to return true in the default case.


However there\'s still a chance that this won\'t work, if the theme you\'re using goes directly to get_post_thumbnail_id(). To make that work, you\'ll need to have an ID for your image: either

  1. upload the image to the media library

  2. pick an out-of-range ID, e.g. -123, to be the thumbnail attachment ID and then fake the image by hooking image_downsize (I think!)

    function image_downsize_default_thumbnail( $downsize, $id, $size )
    {
        if ( $id == -123 )
        {
            return array(
                \'https://upload.wikimedia.org/wikipedia/commons/f/f9/Google_Lens_-_new_logo.png\',
                1024, 1024, false );
        }
        return $downsize;
    }
    

and then add a default_post_metadata hook to fill in the missing thumbnail ID when absent, which is the postmeta key _thumbnail_id:

function default_post_metadata__thumbnail_id( $value, $object_id, $meta_key,
                                              $single, $meta_type )
{
    if ( \'_thumbnail_id\' == $meta_key )
    {
        $value = -123; // the attachment ID for the default image
    }
    return $value;
}
add_filter( \'default_post_metadata\', \'default_post_metadata__thumbnail_id\', 10, 5 );

(We can ignore $single as get_metadata_default() will wrap the value in an array if necessary, although get_post_thumbnail_id() passes $single = true anyway.)

With this filter you shouldn\'t need to hook has_post_thumbnail and post_thumbnail_html, as it should pick up the default image as if it were the real thumbnail. You could look up the default ID from a post or from an option here too if you\'d prefer rather than hard-coding it.

相关推荐

Responsive header images

我刚刚建立了一个WordPress网站,但我的其他WordPress网站都有同样的问题:标题图像没有响应。不管屏幕有多小,它都有2000像素宽。我尝试了各种修复,从添加自定义CSS到安装特殊插件,但都没有成功。我最终通过选择不显示标题图像,然后打开文件标题来修复它。并手动在标题上方插入指向图像的链接。它工作得很好,但有两个注意事项。网站标题(在h1标签中)现在位于标题图像下方,而不是上方。此外,此修复程序仅适用于主页。我还没有弄清楚我要为其他页面做什么,除非我选择只在主页上使用标题图像。所以在我继续之前,