Numbering Image List in Gallery

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

Read More

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

Related posts

Leave a Reply

1 comment

  1. 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:

    .gallery-number 
    {
        position: absolute;
        left:0;
        top: 1em;
    }