Blog / WordPress/ How to Count Images in a WordPress Post

How to Count Images in a WordPress Post

WordPress统计文章内图片数量总数

WordPress does not include a built-in function to count images within a post, so you need to add custom code to implement this feature.

This is a relatively simple task that can be accomplished with just a few lines of code. While minor, it can be a useful addition to your theme.

How to Use

First, add the following code to your theme's functions.php file.

// WordPress: Get the number of images in a post
if ( ! function_exists( 'get_post_images_number' ) ) {
    function get_post_images_number() {
        global $post;
        $content = $post->post_content;
        preg_match_all( '/<img.*?(?: |\t|\r|\n)?src=[\'"](.+?)[\'"]/i', $content, $result, PREG_PATTERN_ORDER );
        return count( $result[1] );
    }
}

Then, in the location where you want to display the image count (e.g., within your post template), add the following call.

Note: This code must be placed inside the WordPress main Loop to ensure the $post object is available.

<?php echo get_post_images_number() . ' images'; ?>

Code Explanation & Optimization

The original regular expression was overly complex. The provided code includes optimizations:

  1. Simplified the regex to focus on matching the src attribute value.
  2. Removed the s modifier (dot matches all) from the pattern as it's unnecessary for matching <img> tags.
  3. Uses a more standard quote escaping pattern ['"].

For more precise matching of WordPress media library images (which may include attributes like data-src), consider using the get_media_embedded_in_content() function. However, the provided code is sufficient for counting standard <img> tags.

Post a Comment

Your email will not be published. Required fields are marked with *.