I’m trying to control the output of the random image within this bit of code. The end goal is to NOT output the width and height attributes for the image.

I want this:

<img src="https://wordpress.stackexchange.com/questions/53524/URL HERE" alt="ALT HERE"/>

BUT I DON’T WANT THIS (which is what the code below currently outputs):

<img src="https://wordpress.stackexchange.com/questions/53524/URL HERE" alt="ALT HERE" width="200px" height="200px" />

My code:

$thumb_id = get_post_thumbnail_id(get_the_ID());

$args = array(
    'order' => 'ASC',
    'orderby' => 'rand',
    'post_type' => 'attachment',
    'post_parent' => $post->ID,
    'post_mime_type' => 'image',
    'post_status' => null,
    'numberposts' => 1,
    'exclude' => $thumb_id
);

$attachments = get_posts($args);
if ($attachments) {
    foreach ($attachments as $attachment) {
        echo wp_get_attachment_image($attachment->ID, 'full', false);
    }
}

1 Answer
1

Use wp_get_attachment_image_src() and build a simplified img element. You may use something like the following code as a replacement for wp_get_attachment_image():

function wpse_53524_get_image_tag( $attach_id, $size, $icon, $alt="" )
{
    if ( $src = wp_get_attachment_image_src( $attach_id, $size, $icon ) )
    {
        return "<img src="https://wordpress.stackexchange.com/questions/53524/{$src[0]}" alt="$alt" />";
    }

}

Put the function above into your theme’s functions.php. Call it like wp_get_attachment_image():

foreach ( $attachments as $attachment ) {
    echo wpse_53524_get_image_tag( $attachment->ID, 'full', false );
}

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *