[英]Wordpress add responsive srcset header image to theme
WP 在 4.4 版中为缩略图和发布图像引入了对 srcset 的支持。 但是我找不到使页面 header 响应的方法。 以下是我如何嵌入页面 header:
<img src="<?php header_image() ?>" alt="">
这会在src中加载 header 图像(可以在后端 > 设计 > 自定义中上传)。 但我宁愿包含此图像的所有自定义图像大小(我在 functions.php 中添加)并将它们放在srcset属性中。 但是header好像只有一种尺寸?
这不是一件容易的事,但这就是您使Header图像(横幅)以srcset响应的方式。
ps .:请解决此问题,wordpress! 响应头应该是srcset更新的一部分。
解决方案:我们从不使用WP header_image();
函数,但仅将自定义标头用作我们图像的“上传器”,然后将其手动嵌入:
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 x 300像素(长宽比为3:2)。 所以我添加了2x和4x版本。 不要忘记通过插件重建缩略图。
最后,将自定义标题图片的尺寸设置为缩略图的最大版本很重要。 这是因为WP将图像缩小到此尺寸,并基于该缩小的图像创建其他尺寸的后缀。 在这种情况下,请在functions.php中搜索您的自定义标头,并将width和height设置为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' );
现在可以使用the_header_image_tag();
.
您可能想使用它来避免 WP 对响应图像的高度和宽度进行硬编码:
the_header_image_tag( array(
'width' => "",
'height' => "",
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.