WordPress the_content() return only one image from a specific category

I am working on a WordPress website and I am using a loop to get all the posts that have title and body contain an image.

But the problem is that it returns me all the titles but not all the images. I don’t understand why.

Read More

Here is the code:

<?php  query_posts('cat=17&order=ASC');
remove_filter('the_content', 'wpautop');

if (have_posts()) : while (have_posts()) : the_post();
    ?>
    <div class="photos">
        <?php $args = array('post_type' => 'attachment', 'numberposts' => 34, 'post_status' => null, 'post_parent' => $post->ID);
        $attachments = get_posts($args);
        if ($attachments) {
            foreach ($attachments as $attachment) {
                ?>
                <a href="<?php echo $attachment->guid;?>" class="lb_gallery"><?php the_content();?></a>
            <?php
            }
        }?>
        <div class="fotos-desc">
            <span><?php the_title();?></span>
        </div>
    </div>

<?php endwhile; ?>
<?php endif; ?>

And here is the output on front-end:
enter image description here

In the above image you can see titles like foto-1, foto-2, foto-3 and so on. All these titles are coming through loop but it displays the image for the first one only but all posts are having the image as in the foto-1.

Related posts

Leave a Reply

2 comments

  1. You are trying to get the ID via $post->ID, but that will only return the post ID of the first post. You can use global $post; before the args array, or much simpler replace $post->ID by the function get_the_ID().

    $args = array('post_type' => 'attachment', 'numberposts' => 34, 'post_status' => null, 'post_parent' => get_the_ID());
    
  2. The problem here lies in the fact that you have a nested Loop which is not being terminated correctly. The inner get_posts() is upsetting your outer query_posts loop because you’re not resetting this loop when you’re done. Try this:

    <?php  query_posts('cat=17&order=ASC');
    remove_filter('the_content', 'wpautop');
    
    if (have_posts()) : while (have_posts()) : the_post();
        ?>
        <div class="photos">
            <?php $args = array('post_type' => 'attachment', 'numberposts' => 34, 'post_status' => null, 'post_parent' => $post->ID);
            $attachments = get_posts($args);
            if ($attachments) {
                foreach ($attachments as $attachment) {
                    ?>
                    <a href="<?php echo $attachment->guid;?>" class="lb_gallery"><?php the_content();?></a>
                <?php
                }
    
                // restore loop
                wp_reset_postdata();
    
            }?>
            <div class="fotos-desc">
                <span><?php the_title();?></span>
            </div>
        </div>
    
    <?php endwhile; ?>
    <?php endif; ?>
    

    All I’ve done is added a wp_reset_postdata() when you’re done with the inner loop to restore your outer one.