2017-01-31 99 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