大方形wordpress发布缩略图

Cip*_*ian 2 php wordpress

有谁知道如何获得方形wordpress缩略图?

如果我使用它,图像不是方形的

<?php the_post_thumbnail( array(205,205) ); ?>
Run Code Online (Sandbox Code Playgroud)

但如果我这样做,它们就是方形的

<?php the_post_thumbnail( array(135,135) ); ?>
Run Code Online (Sandbox Code Playgroud)

我需要创建一个缩略图库,让我们说300 x 300平方的图像.

Ger*_*der 6

您必须先创建自己的图片大小.这是通过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;
}
Run Code Online (Sandbox Code Playgroud)

这将为您的主题添加对缩略图的支持,如果它还没有.它将创建一个新的图像尺寸,裁剪300x300像素.第二个函数为它提供了更好的描述,并确保它将显示在媒体插入对话框中.

然后你可以像这样使用它.

<?php the_post_thumbnail( 'square-large' ); ?>
Run Code Online (Sandbox Code Playgroud)

您可以在functions.php主题中添加这些行.如果你想确保在主题更新时不会覆盖这些行我强烈建议创建一个子主题,你可以在这里阅读如何做到这一点.

这不会影响现有图像.您可以使用以下代码重新创建缺少的缩略图:

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();
Run Code Online (Sandbox Code Playgroud)

这只需要运行一次.