I am trying to display wordpress image using it ID but the code i use is giving an error which is
Warning: count(): Parameter must be an array or an object that implements Countable in /var/www/wordpress/wp-content/themes/monstajamss/template-parts/content-article.php on line 10
This is my code
<div class="image large"> <?php $thumb_id = get_post_thumbnail_id(get_the_ID()); $alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true); if(count($alt)) ?> <img src="<?php the_post_thumbnail_url('large-size'); ?>" alt="<?php echo $alt; ?>"> </div>
Advertisement
Answer
You are just using get_post_meta
incorrectly – it returns an array by default, but you are passing in true
as the third parameter which changes it to return a single value only – see the Code Reference for get_post_meta.
Therefore your return value is not array, so you don’t need to try count (which only works with arrays) or anything to evaluate an array of values before using it – it already has a single value so you just need to do the following:
<div class="image large"> <?php $thumb_id = get_post_thumbnail_id(get_the_ID()); $alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true); ?> <img src="<?php the_post_thumbnail_url('large-size'); ?>" <?php // only include the alt attrib if the alt text is not empty // (or you could set a default value, or whatever else you might want to do) if ($alt): ?> alt="<?php echo $alt; ?>" <?php endif; ?> /> </div>