如何强制WordPress帖子缩略图以固定大小显示?

时间:2016-07-10 10:51:55

标签: wordpress

我希望后缩略图图像以固定大小(大)显示,无论如何。如果全尺寸图像较大,请使用较大的图像(并且不要缩小整个图像)。如果全尺寸图像较小,请使用img元素的完整大小,设置宽度/高度属性,并让浏览器进行扩展。一直玩get_the_post_thumbnail和条件一段时间,但没有弄乱宽度/高度属性而没有弄乱。

有谁愿意分享清洁解决方案?

3 个答案:

答案 0 :(得分:2)

重新检查您的主题支持add_theme_support('post-thumbnails');

默认WordPress缩略图

the_post_thumbnail( 'thumbnail' );     // Thumbnail (150 x 150 hard cropped)
the_post_thumbnail( 'medium' );        // Medium resolution (300 x 300 max height 300px)
the_post_thumbnail( 'medium_large' );  // Medium Large (added in WP 4.4) resolution (768 x 0 infinite height)
the_post_thumbnail( 'large' );         // Large resolution (1024 x 1024 max height 1024px)
the_post_thumbnail( 'full' );          // Full resolution (original size uploaded)

如果您需要特定的分辨率

the_post_thumbnail( array(500, 500) );  // 500x500 dimension 

发布缩略图链接到大图像尺寸您可以通过更改large

来更改尺寸
if ( has_post_thumbnail() ) {
    $large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'large' );
    if ( ! empty( $large_image_url[0] ) ) {
        printf( '<a href="%1$s" alt="%2$s">%3$s</a>',
            esc_url( $large_image_url[0] ),
            esc_attr( get_the_title_attribute( 'echo=0' ) ),
            get_the_post_thumbnail()
        );
    }
}

您还可以在主题功能中创建自定义精选图片尺寸

 add_image_size( 'custom-thumb', 300, 300); //Simple widget size
 add_image_size( 'sidebar-thumb', 120, 120, true ); // Hard Crop Mode
 add_image_size( 'homepage-thumb', 220, 180 ); // Soft Crop Mode
 add_image_size( 'singlepost-thumb', 590, 9999 ); // Unlimited Height Mode

以下是如何在主题的functions.php文件中创建自定义特色图片尺寸的示例。

if ( function_exists( 'add_theme_support' ) ) {
    add_theme_support( 'post-thumbnails' );
    add_image_size( 'custom-thumb', 300, 300); // 300 pixels wide 
 }

在WordPress主题中显示其他图片尺寸

the_post_thumbnail( 'your-specified-image-size' ); //Example singlepost-thumb

答案 1 :(得分:0)

我会尝试这个解决方案:

1)添加到functions.php这个:add_theme_support( 'post-thumbnails' );

2)然后在wordpress loop添加:<?php echo get_the_post_thumbnail(get_the_ID(), 'full'); ?>

答案 2 :(得分:0)

这就是我想出的。这太可怕了,但我发现在$hwstring中找不到wp_get_attachment_image问题的其他一半方法。

$image_data = wp_get_attachment_image_src( get_post_thumbnail_id(), 'full' );
$lw = get_option( "large_size_w");
// Scale up if full version size is smaller than large
if ($image_data[1] < intval($lw)) {
    $ratio = $lw / $image_data[1];
    $h = round($ratio * $image_data[2]);
    $thumb = get_the_post_thumbnail( null, 'full', array(title => get_the_title()));
    $thumb = preg_replace('#\s(width)="[^"]+"#', ' width="'.$lw.'"', $thumb);
    echo preg_replace('#\s(height)="[^"]+"#', ' height="'.$h.'"', $thumb);
} else {
    the_post_thumbnail('large', array(title => get_the_title() ) );
}