猿问

WordPress:使用带有 wp_get_attachment_image 的 <picture>

我想将<picure>-tag 与 function一起使用wp_get_attachment_image。目前我得到一个<img>带有srcset. 这很好,但是有什么方法可以将其更改为<picure>包含多个来源的 -tag 吗?像这样:


<picture>

  <source media="(min-width: 56.25em)" srcset="large.jpg 1x, large@2x.jpg 2x">

  <source media="(min-width: 37.5em)" srcset="medium.jpg 1x, medium@2x.jpg 2x">

  <source srcset="small.jpg 1x, small@2x.jpg 2x">

  <img src="fallback.jpg" alt="">

</picture>

我需要它,因为我想显示图像的第二个版本。所以我可以在一个标签中拥有水平和垂直图像<picture>。像这样:


<picture>

  <source media="(min-width: 38em)" srcset="art-direction-horizontal.jpg">

  <source srcset="art-direction-vertical.jpg">

  <img src="art-direction-vertical.jpg" alt="">

</picture>


温温酱
浏览 125回答 1
1回答

慕标琳琳

从 5.6.0 开始,我们有了一种包装 img 元素的方法。apply_filters( 'wp_get_attachment_image', $html, $attachment_id, $size, $icon, $attr );过滤器不提取 post_id 而是提取 attachment_id。因此,如果您想系统地激活该功能,您应该通过帖子元链接附件及其移动图像。function wrap_wp_get_attachment_image_with_picture_tag( $html, $attachment_id, $size, $icon, $attr ){&nbsp; &nbsp; if ( is_admin() || $size == 'medium' || $size == 'thumbnail' ) return $html;&nbsp; &nbsp; if ( $mobile_id = get_post_meta( $attachment_id, '_meta_key_of_mobile_picuture_id', true ) ){&nbsp; &nbsp; &nbsp; &nbsp; $mobile_srcset = wp_get_attachment_image_srcset( $mobile_id, 'medium_large' );&nbsp; &nbsp; &nbsp; &nbsp; $html = '<picture><source media="( max-width : 782px )" srcset="'.$mobile_srcset.'">'.$html.'</picture>';&nbsp; &nbsp; }&nbsp; &nbsp; return $html;}add_filter( 'wp_get_attachment_image', 'wrap_wp_get_attachment_image_with_picture_tag', 10, 5 );
随时随地看视频慕课网APP
我要回答