How To Add Image Counter/Numbering on WordPress?

I created a post about how to make a numbering gallery in WordPress, but in this article, i’m going to create an image counter function, which will show the image number.

So let’s start.

JavaScript

To count the images on a particular page, you need a few lines of JavaScript. Here is the script, you just need to copy and paste it on your WordPress website.

I use WPCode Plugin to add JavaScript to my wordpress website.

document.addEventListener('DOMContentLoaded', function() {
    // Get all images in the gallery
    const galleryImages = document.querySelectorAll('.imagecounter');
    
    // Calculate the total number of images
    const totalImages = galleryImages.length;
    
    // Loop through each image and set the content dynamically
    galleryImages.forEach((image, index) => {
        // Create the content in "X/Y" format
        const content = (index + 1) + ' / ' + totalImages;
        
        // Set the pseudo-element content using JavaScript
        image.style.setProperty('--dynamic-content', `'${content}'`);
    });
});

Add the CSS

To show the counter and style things up, we definitely need CSS, here is the CSS code below, you can copy and paste it to the ‘Additional CSS’ section on your WordPress.

.imagecounter {
    position: relative;
    counter-increment: gallery-counter;
}

.imagecounter::before {
    content: var(--dynamic-content);
    position: absolute;
    top: 10px;
    left: 10px;
    background-color: rgba(183, 0, 113, 1);
    color: #fff;
    padding: 1px 10px;
    border-radius: 94px;
    font-size: 16px;
    font-weight: bold;
    z-index: 1;
}

*Note: You can customize the CSS to change the look as you need.

Add the CSS Class to Images

Now, everything is ready, you just need to put the CSS Class on your images, in our case the CSS Class is “imagecounter”, you can use the same or change it.

Note: You have to put the CSS Class “imagecounter” to all the images you want to have that number counter.

Final Look

Here we have the final look,

Notes:

  1. If you are using inside a Gallery, make sure to put the class to all the images, and you don’t need to put the class in the Gallery.
  2. This will not restart the counting, if you want to repeat the counting multiple times on the same page, it will not work.
  3. Tip: If you don’t want to add the class all the time, make a reusable block in your WordPress, so you can use that whenever you like.

Leave a Comment

GET WEEKLY FREE WEB TIPS

Subscription Form