php – 将属性添加到wp_get_attachment_image

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 将属性添加到wp_get_attachment_image脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试为wp_get_attachment_image的结果添加一个属性.

我想使用jquery lazyload来处理我的帖子缩略图的加载,为此我需要将一个data-original =属性添加到< img>标签wp_get_attachment_image正在创建.

我试过了:

$imgsrc = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID),"full" );
$imgsrc = $imgsrc[0];
$placeholderimg = wp_get_attachment_image( 2897,"full",array('data-original'=>$imgsrc) );

但它没有像我预期的那样添加数据属性.

<img class="attachment-full" width="759" height="278" alt="..." src="..."></img>

看一下wp_get_attachment_image函数,看起来它应该可以工作:

function wp_get_attachment_image($attachment_id,$size = 'thumbnail',$icon = false,$attr = '') {


    $htML = '';

    $image = wp_get_attachment_image_src($attachment_id,$size,$icon);

    if ( $image ) {

        list($src,$width,$height) = $image;

        $hwstring = image_hwstring($width,$height);

        if ( is_array($size) )

            $size = join('x',$size);

        $attachment =&amp; get_post($attachment_id);

        $default_attr = array(

            'src'   => $src,'class' => "attachment-$size",'alt'   => trim(strip_tags( get_post_meta($attachment_id,'_wp_attachment_image_alt',true) )),// Use Alt field First

            'tITle' => trim(strip_tags( $attachment->post_title )),);

        if ( empty($default_attr['alt']) )

            $default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not,Use the Caption

        if ( empty($default_attr['alt']) )

            $default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally,use the title



        $attr = wp_parse_args($attr,$default_attr);

        $attr = apply_filters( 'wp_get_attachment_image_attributes',$attr,$attachment );

        $attr = array_map( 'esc_attr',$attr );

        $html = rtrim("<img $hwstring");

        foreach ( $attr as $name => $value ) {

            $html .= " $name=" . '"' . $value . '"';

        }

        $html .= ' />';

    }



    return $html;

}

我哪里错了?

解决方法

我没有测试过,但我认为问题是你的数组应该是 wp_get_attachment_image的第四个参数,而不是第三个.

所以

$placeholderimg = wp_get_attachment_image( 2897,array('data-original'=>$imgsrc) );

应该

$placeholderimg = wp_get_attachment_image( 2897,false,array('data-original'=>$imgsrc) );

假设您对$icon参数的认值(false)感到满意.

脚本宝典总结

以上是脚本宝典为你收集整理的php – 将属性添加到wp_get_attachment_image全部内容,希望文章能够帮你解决php – 将属性添加到wp_get_attachment_image所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。