NB: Make sure you do a back up of your theme, files and database before attempting the tutorials
Last modified : Oct 01 2022
Estimated reading time : 1 minute, 6 seconds - 124 words
Share the post "Display the Number of Images Attached to Post IDs"
In this tutorial, we will create a few lines of code that will allow you to display the number of images attached to a Post ID with the help of a WordPress query.
First, in our query, we will need the $attachments variable which contains get_children of all images linked to Post or Post Type. And then we create a new $count variable that will count the images.
With a foreach, we will display Post ID’s number of images as long as the query will find Post Ids.
Here’s the code to use with your Post or Post Type query.
global $post;
$attachments = get_children (
array(
'post_parent' => $post->post_parent,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID' )
);
$count = count( $attachments );
$specific = array();
$i = 1;
foreach ( $attachments as $attachment ) {
$specific[$attachment->ID] = $i;
++$i;
}We display the results of the loop the number of images attached to the selected Post ID:
echo $count;