• Resolved Linosa

    (@linosa)


    Hi,

    I’m using a code to get the latest image from a post. It works fine, except for the fact that if the next post dosen’t have an image, it shows the precious posts image insted. Any suggestions how to change that?

    Here’s my code:

    <?php
    $images = get_children( 'post_type=attachment&post_mime_type=image&post_parent=' . get_the_id() );
    foreach($images as $attachment_id => $attachment ) : ;
    $image = wp_get_attachment_image_src( $attachment_id, $size='medium');
    endforeach;
    ?>
      <img src="<?php echo $image[0]; ?>" alt=""/>
Viewing 5 replies - 1 through 5 (of 5 total)
  • before your code snippet, set the $image variable to empty:
    $image[0] = '';
    or a default image url:
    $image[0] = 'http://defaultimageurl';

    if you use the empty option, you can even check before you output an empty img tag:

    <?php if($image[0]!='') { ?><img src="<?php echo $image[0]; ?>" alt=""/><?php } ?>

    (untested)

    Thread Starter Linosa

    (@linosa)

    thank you, I’ll try.

    Thread Starter Linosa

    (@linosa)

    It works perfectly. Thank you!
    Do you know a way to change the code to get the latest upload insted of the first?

    Do you know a way to change the code to get the latest upload insted of the first?

    try to change this section (shown after changes):

    foreach($images as $attachment_id => $attachment ) : ;
    $image = wp_get_attachment_image_src( $attachment_id, $size='medium');
    break; //leave the loop after the first image
    endforeach;

    (totally untested)

    Thread Starter Linosa

    (@linosa)

    I solved it like this:

    <?php
    $image[0] = '';
    $images = get_children( 'post_type=attachment&post_mime_type=image&order=ASC&order_by=post_date&post_parent=' . get_the_id() );
    foreach($images as $attachment_id => $attachment ) : ;
    $image = wp_get_attachment_image_src( $attachment_id, $size='thumbnail');
    endforeach;
    ?>

    Thanks for your help!

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Get the latest image’ is closed to new replies.