[英]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.