Wordpress在主题中添加响应式srcset标题图像
WP在4.4版本中为缩略图和后期图像引入了对srcset的支持。但我找不到一种方法来使页面标题响应。这里是我嵌入页标题:Wordpress在主题中添加响应式srcset标题图像
<img src="<?php header_image() ?>" alt="">
这会将头图像中的SRC(其可以在后端>设计>自定义被上传)。但我宁愿包含此图像的所有自定义图像大小(我在functions.php中添加的),并将它们放入属性的一个srcset属性中。但是头部似乎只有一个尺寸?
这不是一件容易的事情,但这是您如何使标题图片(横幅)响应srcset。
ps .:请解决这个,wordpress!响应头文件应该是srcset更新的一部分。
解决方法:我们从来不使用WP header_image();
功能,而仅仅只是使用了自定义标题为“上载”为我们的形象,我们再手动嵌入:
- 提取头图像的attachement ID
- 手动负载src和这个attachement ID的srcset
的header.php
<?php
// Extract header attachement ID
$data = get_theme_mod('header_image_data');
$data = is_object($data) ? get_object_vars($data) : $data;
$header_id = is_array($data) && isset($data['attachment_id']) ? $data['attachment_id'] : false;
if($header_id) :
// Set image sources manually
$src = wp_get_attachment_image_src($header_id, 'thumbnail-head')[0];
$srcset = wp_get_attachment_image_srcset($header_id, 'thumbnail-head'); ?>
<img id="masthead-bg" src="<?php echo $src ?>" srcset="<?php echo $srcset ?>" sizes="100vw" alt="">
<?php endif; ?>
在此示例中,thumbnail-head
是我的目标图像大小和宽高比。你可以使用任何你想要的尺寸(需要有固定的高宽比)。我们现在必须将这个图像大小添加到functions.php文件。为了获得更大的这种缩略图大小(在srcset嵌入),你也有更多的尺寸增加了的functions.php:
的functions.php
add_image_size('thumbnail-head', 450, 300, true);
add_image_size('thumbnail-head-2x', 900, 600, true);
add_image_size('thumbnail-head-4x', 1800, 1200, true);
我的缩略图的大小是450 ×300像素(3:2宽高比)。所以我增加了一个2x和4x版本。不要忘记通过插件重建缩略图。
最后,将自定义标题图像的尺寸设置为缩略图的最大版本很重要。这是因为WP会将图像裁剪到这个尺寸,并根据这个裁剪后的图像创建其他尺寸的字。在这种情况下,在functions.php中搜索自定义标题,并将宽度和高度设置为1800和1200.我们还禁用“flex-width”和“flex-height”以强制添加图像大小相同的宽高比。
的functions.php
function fs_custom_header_setup() {
add_theme_support('custom-header', apply_filters('fs_custom_header_args', array(
'default-image' => '',
'header-text' => false,
'default-text-color' => 'ffffff',
'width' => 1800,
'height' => 1200,
'flex-width' => false,
'flex-height' => false,
'wp-head-callback' => 'fs_header_style',
)));
}
add_action('after_setup_theme', 'fs_custom_header_setup');
更新: 我可以使用'wp_get_attachment_image_srcset(get_post_thumbnail_id(), '尺寸'); '获取图像ID的srcset。问题:我无法找到获取标题图像ID的方法。这里描述的方法似乎不再有效:http://nickohrn.com/2013/09/get-attachment-id-wordpress-header-image/#comment-165155 –