Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

What I want to do seems to be simple but I can't get around it. I'd like to get the latest post that has an image attachment. A little help would be appreciated. Thanks

Lita

share|improve this question
    
What have you tried so far? –  s_ha_dum Mar 7 '13 at 15:15
    
What I had so far was getting the latest attachment post but thank you bcorkins solution works. –  Lita Mar 8 '13 at 6:43

1 Answer 1

up vote 1 down vote accepted

This is a tricky one. If you wanted to get the latest image attachment and display the post associated with it, you could use:

$attachments = get_posts('post_type=attachment');
$first_attachment_post = get_post($attachments[0]->post_parent);

To get the latest post, but only if it has an attachment, I think the only way to do it would be with two nested queries. For example:

$the_query = new WP_Query( $args );
while ( $the_query->have_posts() ) : $the_query->the_post();

        $attachments = get_children( array('post_parent' => get_the_ID(), 'post_type' => 'attachment', 'post_mime_type' => 'image') );

        if ( $attachments ) {
            // Post output here will only be display if attachments are found
            echo '<li>' . get_the_title() . '</li>';
        }
endwhile;
share|improve this answer
    
Thank you, it works!! –  Lita Mar 8 '13 at 6:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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