为了账号安全,请及时绑定邮箱和手机立即绑定

WordPress:使用带有 wp_get_attachment_image 的 <picture>

WordPress:使用带有 wp_get_attachment_image 的 <picture>

PHP
温温酱 2022-10-09 19:52:36
我想将<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>
查看完整描述

1 回答

?
慕标琳琳

TA贡献1830条经验 获得超9个赞

从 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 ){

    if ( is_admin() || $size == 'medium' || $size == 'thumbnail' ) return $html;

    if ( $mobile_id = get_post_meta( $attachment_id, '_meta_key_of_mobile_picuture_id', true ) ){

        $mobile_srcset = wp_get_attachment_image_srcset( $mobile_id, 'medium_large' );

        $html = '<picture><source media="( max-width : 782px )" srcset="'.$mobile_srcset.'">'.$html.'</picture>';

    }

    return $html;

}

add_filter( 'wp_get_attachment_image', 'wrap_wp_get_attachment_image_with_picture_tag', 10, 5 );



查看完整回答
反对 回复 2022-10-09
  • 1 回答
  • 0 关注
  • 124 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号