我试图实现的是为特定的帖子类型(书籍)定义一个特定的图像大小(肖像缩略图),以便只有此帖子类型生成此缩略图大小,并且我不会通过为站点上的所有其他帖子类型创建此缩略图格式来浪费磁盘空间。
我试图遵循this answer 对于一个类似的问题,这是我到目前为止提出的代码:
// Delete all intermediate image sizes
add_filter( \'intermediate_image_sizes\', \'__return_empty_array\', 99 );
// Add custom image sizes depending on post type
function add_custom_post_types_image_sizes( $metadata, $attachment_id ) {
$post_parent_id = wp_get_post_parent_id( $attachment_id );
// For books
if ( \'book\' === get_post_type( $post_parent_id ) ) {
// Add portrait thumbnail
add_image_size( \'portrait_thumbnail\', \'150\', \'215\', true );
// This doesn\'t work :
$file = get_attached_file( $attachment_id );
wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
}
return $metadata;
}
add_filter( \'wp_generate_attachment_metadata\', \'add_custom_post_types_image_sizes\', 10, 2 );
SO网友:middlelady
您可以尝试以下操作(未测试):
// Add image sizes for book outside
add_image_size( \'book_portrait_thumbnail\', \'150\', \'215\', true );
add_image_size( \'book_portrait_square\', \'300\', \'300\', true );
// Delete all intermediate image sizes
add_filter( \'intermediate_image_sizes\', \'custom_image_sizes\', 99 );
function custom_image_sizes( $image_sizes ) {
//In case of book return book sizes array
if( isset($_REQUEST[\'post_id\']) && \'books\' === get_post_type( $_REQUEST[\'post_id\'] ) ){
return array( \'book_portrait_thumbnail\', \'book_portrait_square\' );
}
// Otherwise the other ones
return $image_sizes;
}
当然,这是为了科学。就像其他人建议的那样,我宁愿找一家不同的主机提供商,这与当前的技术服务状态无关。