首页 问答 正文

如何自定义WordPress缩略图?

注册会员 / 悠然自学 / 2023-06-11/ 浏览 113 次

WordPress有一个默认的缩略图功能,在发布文章时,可以手动选择一张图片,作为文章的缩略图。但是,有时候我们需要进行更加细致的处理,比如缩略图的大小、裁剪方式等等。在这种情况下,我们需要自定义WordPress缩略图。

可以通过以下步骤来自定义WordPress缩略图:

1.在functions.php中添加自定义缩略图大小:

add_image_size( 'custom-size', 800, 400, true );//第一个参数是缩略图的名称,第二个参数是宽度,第三个参数是高度,第四个参数是是否对图像进行裁剪。  

2.在模板文件中使用自定义缩略图:

the_post_thumbnail( 'custom-size' ); 

以上是自定义缩略图的基本步骤,如果需要更加高级的功能,可以使用以下代码:

add_filter( 'wp_generate_attachment_metadata', 'my_image_size' );
function my_image_size( $metadata ) {
    $upload_dir = wp_upload_dir();

    $file = trailingslashit( $upload_dir['path'] ) . $metadata['file'];

    if ( $size = getimagesize( $file ) ) {
        $image_width    = $size[0];
        $image_height   = $size[1];
        $image_ratio    = $size[2];

        $max_width  = 1200;
        $max_height = 1200;

        $scaling = min( $max_width / $image_width, $max_height / $image_height );

        if ( $scaling < 1 ) {
            $width  = floor( $scaling * $image_width );
            $height = floor( $scaling * $image_height );

            $new_metadata = wp_generate_attachment_metadata( $attachment_id, $file );//这里需要替换为实际的$attachment_id

            if ( is_array( $new_metadata ) && $new_metadata['width'] && $new_metadata['height'] ) {
                $new_metadata['sizes']['custom-size'] = array(
                    'file'   => $new_metadata['sizes']['large']['file'],//这里需要替换为实际的缩略图名称
                    'width'  => $width,
                    'height' => $height,
                    'mime-type' => $new_metadata['sizes']['large']['mime-type']
                );

                wp_update_attachment_metadata( $attachment_id, $new_metadata );//这里需要替换为实际的$attachment_id
            }
        }
    }

    return $metadata;
} 

上面的代码可以实现更加精细的缩略图处理,比如限制缩略图大小、等比例缩放、加上水印等等功能。

大家谈论
    我的见解