How many attachment in a WordPress post has?

There was a case where a client wanted to remove previous and next arrows in attachment images slider. The problem was that she wanted to remove arrows when only one image in WordPress attachment,  arrows still showing when there’re more than one images.

The solution was to found out how many attachment in a WordPress post. There is no conditional tag for this purpose, so we create lines of code. Add following code to WordPress template, for example single.php


<?php

$attachments = get_children(array('post_parent'=>$post->ID));
$nbImg = count($attachments);
if ($nbImg == 1) {
echo 'There is'.$nbImg.' picture on this post.';
}
if ($nbImg > 1) {
echo 'There are '.$nbImg.' pictures on this post.';
}
?>

If there is one image, text should read ‘There is 1 picture on this post’
If there is more than one image, text should read ‘There are 2 pictures on this post

wordpressattachmentnum

 

Summary
Article Name
How many attachment in a WordPress post has?
Description
A way to find out how many attachment in a WordPress post.
Author