2

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="URL HERE" alt="ALT HERE"/>

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

<img src="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);
    }
}

migrated from stackoverflow.com May 28 '12 at 16:56

This question came from our site for professional and enthusiast programmers.

3

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='{$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 );
}
  • Thanks for your help on this. I've got it working now. Thanks. I can be a bit of a fruitbar when it comes to PHP. Out of curiosity, do PHP functions always have to appear in the functions.php file? – egr103 May 29 '12 at 14:01
  • They may be placed almost anywhere. A central place is just easier to work with. – fuxia May 29 '12 at 14:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.