• 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' => get_the_ID()
            ));
    
        	echo count($attachments);
    
        	if(empty($attachments)) {
        		echo ' No image';
        	}else{
        	  echo '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(); ?>
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • The topic ‘Check if post has image’ is closed to new replies.