6

我正在尝试将属性添加到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 =& 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

4

1 回答 1

12

我没有测试过,但我认为问题是你的数组应该是第四个参数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) );

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

于 2013-09-24T11:12:05.250 回答