I am having a wordpress loop that shows all the posts. I need to have a count of all the images for a particular post.
<?php while ( $the_query->have_posts() ) : $the_query->the_post();
$attachments = get_children( array( 'post_parent' => $post->ID, 'post_mime_type' => 'image' ) );
$count = count( $attachments );
$specific = array();
$i = 1;
foreach ( $attachments as $attachment ) {
$specific[$attachment->ID] = $i;
++$i;
} ?> <a href="#"><?php echo $count; ?></a>
<?php endwhile; ?>
the problem is that, it doesn't works and it does not display images count.
here is a solution and for more information visit https://blog.josemcastaneda.com/2014/03/18/get-image-count-in-wordpress-post/
// Get all the galleries in the current post
$galleries = get_post_galleries( get_the_ID(), false );
// Count all the galleries
$total_gal = count( $galleries );
/**
* count all the images
* @param array $array The array needed
* @return int returns the number of images in the post
*/
function _get_total_images( $array ){
$key = 0;
$src = 0;
while ( $key < count( $array ) ){
$src += count( $array[$key]['src'] );
$key++;
}
return intval( $src );
}
echo _get_total_images( $galleries );
You can use basic PHP to do this. Each image begins with a repeatable HTML pattern, so just count the occurrences with substr_count()
:
$image_count = substr_count( get_the_content(), '<img' );
That will give you the number of <img>
's in the post.
You can use Function Reference/get attached media like this:
with the_post();
$count = count( get_attached_media( 'image' ) );
or with post id
$count = count( get_attached_media( 'image', $post->ID ) );
Doc: https://codex.wordpress.org/Function_Reference/get_attached_media