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.

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="https://wordpress.stackexchange.com/questions/78001/<?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.

2 Answers
2

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());

Leave a Comment