将属性添加到wp_get_attachment_image


Add attribute to wp_get_attachment_image

我正在尝试向wp_get_attachment_image的结果添加一个属性。

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

我试过:

$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 =& 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;
 
}

我哪里出错了?

[更新] 有时只需要一双新鲜的眼睛就能发现白痴......多亏了流浪汉,我意识到我只是错过了函数调用中的一个参数:D :P

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

所以

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

应该是

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

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

我个人通过字符串替换解决了这个问题:

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

这不是一个优雅的解决方案,但它可以在某些上下文中工作(例如,您可能将属性保存在字符串中,而不是像您的情况那样作为数组)。