Agregar atributo a wp_get_attachment_image

2 minutos de lectura

avatar de usuario
gpcola

Estoy tratando de agregar un atributo al resultado de wp_get_attachment_image.

Quiero usar jquery lazyload para manejar la carga de las miniaturas de mis publicaciones y para hacerlo necesito agregar un data-original= atribuir a la <img> etiqueta wp_get_attachment_image está creando.

He intentado:

$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) );

Pero no agrega el atributo de datos como esperaba.

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

Mirando a la wp_get_attachment_image Sin embargo, parecería que esto debería funcionar:

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ónde me estoy equivocando?

[update] A veces solo se necesita un nuevo par de ojos para detectar la idiotez… Gracias a vagabundo me di cuenta de que simplemente me perdí un parámetro en mi llamada de función 😀 😛

No lo he probado, pero creo que el problema es que su matriz debería ser el cuarto argumento para wp_get_attachment_imageno el tercero.

Asi que

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

debiera ser

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

suponiendo que esté satisfecho con el valor predeterminado (false) del $icon argumento.

¿Ha sido útil esta solución?