您必须先创建自己的图片尺寸。这是通过add_image_size() 函数完成的。
你可以这样做:
if ( function_exists( 'add_theme_support' ) ) {
add_theme_support( 'post-thumbnails' );
add_image_size( 'square-large', 300, 300, true); // name, width, height, crop
add_filter('image_size_names_choose', 'my_image_sizes');
}
function my_image_sizes($sizes) {
$addsizes = array(
"square-large" => __( "Large square image")
);
$newsizes = array_merge($sizes, $addsizes);
return $newsizes;
}
这将为您的主题添加对缩略图的支持,如果它还没有的话。它将创建一个裁剪为 300x300 像素的新图像大小。第二个函数给出了更好的描述,并确保它会显示在媒体插入对话框中。
那你就可以这样使用了。
<?php the_post_thumbnail( 'square-large' ); ?>
您可以在主题的functions.php 中添加这些行。如果您想确保更新主题时不会覆盖这些行,我强烈建议您创建一个子主题,您可以read here how to do that。
这不会影响现有图像。您可以使用以下代码重新创建丢失的缩略图:
include_once( ABSPATH . 'wp-admin/includes/image.php' );
function regenerate_all_attachment_sizes() {
$args = array( 'post_type' => 'attachment', 'numberposts' => 100, 'post_status' => null, 'post_parent' => null, 'post_mime_type' => 'image' );
$attachments = get_posts( $args );
if ($attachments) {
foreach ( $attachments as $post ) {
$file = get_attached_file( $post->ID );
wp_update_attachment_metadata( $post->ID, wp_generate_attachment_metadata( $post->ID, $file ) );
}
}
}
regenerate_all_attachment_sizes();
这只需运行一次。