WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is there a function that allows me to get the number of photo's attached to a post and that also grabs the url of the first attachment to go to the attachment page for each post?

Here is an example of what i want to accomplish, that i did in photoshop

enter image description here

Do you see the number sixteen next to the thumbnails, thats what i want to accomplish, a code that allows the users to know how many photo's are attached to the current post they are reading and also have the number work as a link.

I want the link to grab the first photo attachment url.

My attachment are set up like this


Is this even possible?

share|improve this question
Just a quick question, assuming that you got this to work and your Permalinks were variables based on an Image count. Wouldn't it be safe to assume your Permalinks would break when /year-month-day/post-title/16 turned to /year-month-day/post-title/17 or even /year-month-day/post-title/15? Maybe I am interpreting your question wrong. – David Mar 24 '12 at 9:25
please take a closer look, because i have explained in the simplest way possible lol, use the image as reference too........ where it has the number "16" that's suppose to be the number of attachments attached to that post, the number should also link to the first attachment in the gallery of that post – Terrell Anderson Mar 24 '12 at 9:45
I just realized that this may be more complicated than i thought and it may need javascript for this function – Terrell Anderson Mar 24 '12 at 9:57

Use following code to do the work :

global $post;
$page_id = $post->ID;
$all_attachments = get_posts( array( 'post_type' => 'attachment','post_mime_type' => 'image', 'post_parent' => $page_id, 'post_status'=>'published',  'numberposts' => -1 ) );

$no_of_photos = count($all_attachments); // Gets the number of photo's attached in $no_of_photos variable
$first_img_URL = get_permalink($all_attachments[0]->ID); // Gets the URL of first attachment in  $first_img_URL variable

In the above code just replace the $page_id to the id of page/post to which the photos are attached.

share|improve this answer
Let me rephrase the question – Terrell Anderson Mar 24 '12 at 5:11
I rephrased the question i hope that helps – Terrell Anderson Mar 24 '12 at 5:21

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.