Blog / WordPress/ How to Get the Total Number of Posts for a Specific Tag in WordPress

How to Get the Total Number of Posts for a Specific Tag in WordPress

WordPress获取指定标签下的文章总数

When developing a WordPress theme, you may need to retrieve the total number of posts assigned to a specific tag. This article provides two reliable methods with ready-to-use code snippets.

Method 1: Get Post Count by Tag ID

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

/**
 * Get post count by tag ID.
 * @param int $tag_id The tag ID.
 * @return int The total number of posts.
 */
function get_tag_post_count_by_id( $tag_id ) {
    $tag = get_term_by( 'id', $tag_id, 'post_tag' );
    if ( ! $tag || is_wp_error( $tag ) ) {
        return 0;
    }
    // _make_cat_compat ensures backward compatibility (optional).
    if ( function_exists( '_make_cat_compat' ) ) {
        _make_cat_compat( $tag );
    }
    return $tag->count;
}

Then, call the function in your template file where you want to display the count:

<?php echo get_tag_post_count_by_id( $tag_id ); ?>

Replace $tag_id with the actual tag ID.

Method 2: Get Post Count by Tag Slug

Similarly, add this function to functions.php:

/**
 * Get post count by tag slug.
 * @param string $tag_slug The tag slug.
 * @return int The total number of posts.
 */
function get_tag_post_count_by_slug( $tag_slug ) {
    $tag = get_term_by( 'slug', $tag_slug, 'post_tag' );
    if ( ! $tag || is_wp_error( $tag ) ) {
        return 0;
    }
    if ( function_exists( '_make_cat_compat' ) ) {
        _make_cat_compat( $tag );
    }
    return $tag->count;
}

Call the function in your template, ensuring you use the correct function name and parameter:

<?php echo get_tag_post_count_by_slug( $tag_slug ); ?>

Replace $tag_slug with the actual tag slug.

Important Notes

  • Error Handling: Both functions check if the tag exists and return 0 if not, preventing warnings.
  • Compatibility: The _make_cat_compat() function is an internal WordPress function for legacy compatibility. It's usually unnecessary in modern versions but is included safely.
  • Usage: You can call these functions anywhere in your theme, such as sidebars, footers, or custom widgets.

Post a Comment

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