这可以通过以下方式完成:
wp_get_attachment_metadata();
wp_update_attachment_metadata();
您将获得它的元数据,并对其进行更改,然后保存它。您获得的$数据数组包含另一个名为sizes的数组,该数组包含连接到附件的所有不同大小的图像。
您希望在上载方便命名的图像时自动更新。我不太明白为什么值得这么做,但让我们看看。
这需要做一点,这可能不是最好的方式,但它会起作用,并会让你知道如何做。
// hooking in to the add_attachment action just like you did
add_action(\'add_attachment\', function ( $post_ID ) {
// we need to work with the database
global $wpdb;
// get the attachment
$post = get_post( $post_ID );
// remove the _x2 suffix to help find the original
$attachment_name = str_replace( \'_x2\', \'\', $post->post_title );
// did this file have an _x2 suffix?
$is_x2 = ( $attachment_name == $post->post_title ) ? FALSE : TRUE;
// get the attachments extension
$extension = pathinfo( $post->guid, PATHINFO_EXTENSION );
// if there is a large file, it would be called:
$large_file = $attachment_name . \'_large.\' . $extension;
// time to see if we have a large file saved
// wordpress stores the relative path from the uploads directory
// we use a like query to find the file in any year/month subdir
$result = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM $wpdb->postmeta
WHERE meta_value LIKE %s",
\'%\' . $wpdb->esc_like($large_file)
));
// did we find a file?
if( !empty( $result ) ) {
// yep we found a file, get its meta
$attachment_meta = wp_get_attachment_metadata( $result->post_id );
// get meta data on the new file
$meta = get_post_meta( $post->ID, \'_wp_attached_file\', TRUE );
// manually read the size of the new image
$upl = wp_upload_dir();
$new_file = $upl[\'basedir\'] . \'/\' . $meta;
$sizes = getimagesize( $new_file );
// what should the thumbnail be called?
// remember we checked if the file had the _x2 suffix before?
$thumb_name = ( $is_x2 ) ? \'x2\' : \'thumb\';
// time to add the new size to the meta data of the large file
$attachment_meta[\'sizes\'][$thumb_name] = array(
\'file\' => basename($post->guid),
\'width\' => $sizes[0],
\'height\' => $sizes[1],
\'mime-type\' => $sizes[\'mime\']
);
// save the new meta data to the large file
wp_update_attachment_metadata( $result->post_id, $attachment_meta );
// now we delete all references to the new file that was uploaded
// by manually deleting it from the database the file will be kept on disk
// this step is optional, Wordpress will behave a bit funny when uploading if used
$wpdb->query($wpdb->prepare(
"DELETE FROM $wpdb->posts
WHERE $wpdb->posts.ID = %d",
$post->ID
));
$wpdb->query($wpdb->prepare(
"DELETE FROM $wpdb->postmeta
WHERE $wpdb->postmeta.post_id = %d",
$post->ID
));
}
});
最后2个删除查询是可选的,您说过您不想在数据库中为新图像添加新条目,这些查询将删除新条目。Wordpress不喜欢删除这些引用,上传时会有点搞笑,但不会破坏任何东西。
现在,您可以像处理其他缩略图一样轻松地获取缩略图。假设您已将大文件作为特色图像附加到帖子:
global $post;
// the filename_large.jpg file
echo get_the_post_thumbnail($post->ID);
// the filename.jpg file
echo get_the_post_thumbnail($post->ID, \'thumb\');
// the filename_x2.jpg file
echo get_the_post_thumbnail($post->ID, \'x2\');
您可以使用保存新附件元数据的$thumb\\u name变量更改缩略图的调用。
无论您是否使用可选的删除查询,这都会起作用,如果您只是为了方便起见,那么我说不要使用查询。如果您确实不希望缩略图显示为单个图像,请使用它们。