您可以通过过滤_thumbnail_id
.
add_filter( \'update_post_metadata\', \'generate_featured_image_sizes\', 10, 5 );
add_filter( \'add_post_metadata\', \'generate_featured_image_sizes\', 10, 5 );
function generate_featured_image_sizes( $check, $object_id, $meta_key, $meta_value, $unique_or_prev ) {
if ( $meta_key == \'_thumbnail_id\' ) {
// regenerate previous featured image thumbs if it exists
if ( false !== ( $prev_thumb_id = get_post_meta( $object_id, \'_thumbnail_id\', true ) ) ) {
$prev_new_metadata = wp_generate_attachment_metadata( $prev_thumb_id, get_attached_file( $prev_thumb_id ) );
if ( ! is_wp_error( $prev_new_metadata ) )
wp_update_attachment_metadata( $prev_thumb_id, $prev_new_metadata );
}
// remove all normal image sizes before we add our filter
cleanup_attachment_images( $meta_value );
// filter image sizes for featured
add_filter( \'intermediate_image_sizes\', \'featured_image_sizes\', 9999 );
// regenerate thumbnails for featured
$new_metadata = wp_generate_attachment_metadata( $meta_value, get_attached_file( $meta_value ) );
if ( ! is_wp_error( $new_metadata ) )
wp_update_attachment_metadata( $meta_value, $new_metadata );
// remove featured sizes from previous featured image
if ( isset( $prev_thumb_id ) && $prev_thumb_id )
cleanup_attachment_images( $prev_thumb_id );
// tidy up
remove_filter( \'intermediate_image_sizes\', \'featured_image_sizes\', 9999 );
}
return $check;
}
function featured_image_sizes( $sizes ) {
return array( \'large\', \'featured\', \'slider\' );
}
function cleanup_attachment_images( $attachment_id ) {
$uploadpath = wp_upload_dir();
$intermediate_sizes = array();
foreach ( get_intermediate_image_sizes() as $size ) {
if ( $intermediate = image_get_intermediate_size( $attachment_id, $size ) )
$intermediate_sizes[] = $intermediate;
}
// remove intermediate and backup images if there are any
foreach ( $intermediate_sizes as $intermediate ) {
/** This filter is documented in wp-admin/custom-header.php */
$intermediate_file = apply_filters( \'wp_delete_file\', $intermediate[ \'path\' ] );
@ unlink( path_join( $uploadpath[ \'basedir\' ], $intermediate_file ) );
}
}
重新创建缩略图只是生成和更新附件元数据的一种情况,因此只要特征图像发生更改,就可以通过重新生成来获得所需的效果。
这将适用于上传,但也适用于更改特色图像。此外,它将为旧缩略图重新生成拇指,使其像一个正常大小的正常图像一样。
使用的原因add_post_metadata
和update_post_metadata
挂钩是为了在数据库中更新当前值之前,我们可以访问当前值。
NOTE为特色图像或编辑器添加媒体弹出窗口之间没有真正的区别,这些链接只是在不同的状态下打开弹出窗口,因此在上传图像时,没有简单的方法来判断请求的状态(特色图像或编辑器),因此我在上面介绍了这种方法。
UPDATE我添加了一个函数,您可以调用该函数来删除附件生成的缩略图集。您可以在生成新的附件元数据之前调用此函数。您甚至可以过滤它删除的图像大小或修改函数,以便可以将它们作为参数传递。