WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

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

While adding images in a post with the gallery shortcode, I want to display an image number as title of the image e.g if there are 3 images in a gallery and displayed as a list, above each image there should be a serial number.

Shown as enter image description here

I can set it afterwards with inline css. I tried alot in media.php, but without success.

share|improve this question
Never really a good idea to hack core files. – Brian Fegter Nov 30 '12 at 17:34
You cannot change the meaning of a question after there are answers. Including a featured image is a new question. It requires specific information about the loop and the placement of that image. – toscho Dec 1 '12 at 12:33
ok sorry , will post another thanks for answer. – busyjax Dec 1 '12 at 12:50
up vote 1 down vote accepted

Set a custom function between the gallery shortcode handler and the output. Catch the img elements and add a static counter. Then return the gallery output to WordPress.

Sample code:

add_action( 'after_setup_theme', 'wpse_74492_replace_gallery_shortcode' );

 * Replace the default shortcode handlers.
 * @return void
function wpse_74492_replace_gallery_shortcode()
    remove_shortcode( 'gallery' );
    add_shortcode( 'gallery', 'wpse_74492_gallery_shortcode' );

function wpse_74492_gallery_shortcode( $attr )
    // Let WordPress create the regular gallery …
    $gallery = gallery_shortcode( $attr );

    $gallery = preg_replace_callback( '~<img~', 'wpse_74492_gallery_callback', $gallery );

    return $gallery;

function wpse_74492_gallery_callback( $matches )
    static $count = 0;
    $count += 1;

    return "<span class='gallery-number'>$count</span>" . $matches[0];

This will insert a <span class='gallery-number'>1</span> into the link. You can position it in CSS with:

    position: absolute;
    top: 1em;
share|improve this answer
where should I add this, media.php or functions.php? – busyjax Dec 1 '12 at 11:16
Your theme’s functions.php. The media.php is a core file, it will be overwritten during the next WordPress update. – toscho Dec 1 '12 at 11:29
What does this mean?? wpse_74492_replace_gallery_shortcode Change it with? – busyjax Dec 1 '12 at 11:35
You can copy the code as it is to the functions.php I have tested it, it works. The naming scheme we use here is wpse for WordPress Stack Exchange plus the question number as prefix to avoid collisions with other people’s code. – toscho Dec 1 '12 at 11:42
Works fine, but it doesn't show count on featured image. – busyjax Dec 1 '12 at 11:53

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.