2017-01-31 101 views
0

我用下面的代码打印出来的srcset为我的形象:wp_get_attachment_image_sizes(“大”)打印小尺寸的

<?php if (function_exists('wp_get_attachment_image_srcset')) :?> 
srcset="<?php echo esc_attr(wp_get_attachment_image_srcset(get_post_thumbnail_id($blog_results->post->ID, 'medium'))); ?>" 
sizes="<?php echo esc_attr(wp_get_attachment_image_sizes(get_post_thumbnail_id($blog_results->post->ID, 'medium'))); ?>" 
<?php endif; ?> 

,我使用的容器具有350像素的宽度,但WordPress的返回此:

sizes="(max-width: 300px) 100vw, 300px" 

我想强制以某种方式获得下一个可用大小,因为图像质量很差。到目前为止,我一直在寻找解决方案,但没有成功。

有没有任何干净的方式可以完成这个没有硬编码“尺寸”?

回答

1

你可能会尝试这种方法。

第一:

//$name = Image size identifier. 
//$width = Image width in pixels. 
//$height = Image height in pixels. 
//$crop =true/false (crop images to specified width and height or resize). 
$name = 'custom-size'; $width = '350px'; $height = '200px'; $crop = true; 
add_image_size($name, $width, $height, $crop); 

检查此链接https://developer.wordpress.org/reference/functions/add_image_size/。 这个函数写在functions.php文件中。现在,您可以在需要的地方使用此自定义大小的图像。

<?php if (function_exists('wp_get_attachment_image_srcset')) :?> 
srcset="<?php echo esc_attr(wp_get_attachment_image_srcset(get_post_thumbnail_id($blog_results->post->ID, 'custom-size'))); ?>" 
sizes="<?php echo esc_attr(wp_get_attachment_image_sizes(get_post_thumbnail_id($blog_results->post->ID, 'custom-size'))); ?>" 
<?php endif; ?> 

现在你可以得到你的愿望形象。

+0

是的,我试过了,但似乎没有工作,至少在我身边。 –

+0

除了硬编码sizes参数外,还找不到解决这个问题的方法。有没有人成功使用上述建议?如果是的话,那么在我的设置中可能还有其他的东西阻止了这个。 –

+1

我有同样的问题。请让我们知道,如果你找到解决办法!我也对尺寸属性进行了硬编码(以获得完全控制,但显然这应该以更智能的方式自动化)。 – emilolsson