Loop through all posts, show attachment if there

I’ve created two simple foreach loops: one for all posts, one for all attachments. I want it show every post title, and if there is an attachment, show that attachment.

I have, thus far:

$get_posts_array = array( 'posts_per_page' => 3, 'post_type' => 'post' );
$get_posts = get_posts( $get_posts_array );

foreach ($get_posts as $post)
{
    the_title();

    $get_images_array = array( 'posts_per_page' => 1, 'post_type' => 'attachment' );
    $get_images = get_posts($get_images_array);

    if ($get_images)
    {
        foreach ( $get_images as $post )
        {
        ?>
            <li> <?php the_attachment_link( $post->ID ) ;?> </li>
        <?php
        } 
    }
}
?>

However, it is not working as expected.

It retrieves every post title, but uses the same first attachment for all posts.

Any help would be great (I’m inexperienced with PHP, so this could be completely buggy).

Read more here:: Loop through all posts, show attachment if there

Leave a Reply

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