【问题标题】:Add attribute to wp_get_attachment_image将属性添加到 wp_get_attachment_image
【发布时间】:2013-09-24 10:28:34
【问题描述】:

我正在尝试为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

【问题讨论】:

    标签: php jquery wordpress


    【解决方案1】:

    我没有测试过,但我认为问题在于您的数组应该是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) 感到满意。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-02
      • 1970-01-01
      • 1970-01-01
      • 2014-08-29
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      相关资源
      最近更新 更多