0

I'm displaying a list of posts and I want to indicate if the posts have images.

I'm using this code to check if a post has an image.

<?php

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

    echo count($attachments);

    if(count($attachments) > 0) { 
        echo 'image';
    }else{
      echo 'No image';
    }

?>

Some of the posts have images but it echo's 'No image'

Is there a better way to check if a post has an image.

  <?php get_header(); ?>

    <section class="allIdeas">

        <?php
            $allideas_args  = array(
                'post_type' => 'post',
                'order' => 'ASC',
                'orderby' => 'date',
                'posts_per_page' => 10,
            );

            $allideas_loop = new WP_Query($allideas_args);

            if($allideas_loop->have_posts()):
                while($allideas_loop->have_posts()):
                    $allideas_loop->the_post();

        ?>


        <div class="ideaPost">

            <a href="<?php echo get_permalink($post->ID); ?>">  
                <div class="ideaPost__Info">
                    <?php

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

                        echo count($attachments);

                        if(count($attachments) > 0) { 
                            echo 'image';
                        }else{
                            echo ' No image';
                        }

                    ?>

                </div>
                <h3 ><?php the_title(); ?></h3>
                <h4>by </h4>

                <?php the_excerpt(); ?>
            </a>
        </div>  

        <?php
            endwhile;
            endif;
        ?>

        <?php wp_reset_postdata(); ?>

    </section>  

  <?php get_footer(); ?>    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.