Forums

[resolved] Count number of posts in a single tag? (6 posts)

  1. Rookje
    Member
    Posted 9 months ago #

    There are a lot of topics similar to this one, but I can't find exactly what I need.

    I need a way to get the # (count) of how many posts are under a specific tag by name.

    I'm using this, but it doesn't seem to work:

    function get_posts_count_by_tag($tag_name)
    {
        $tags = get_tags("search=".$tag_name);
        return $tags[0]->count;
    }
  2. vtxyzzy
    Member
    Posted 9 months ago #

    Give this a try:

    function get_posts_count_by_tag($tag_name)
    {
        $tags = get_tags(array ('search' => $tag_name) );
        return $tags[0]->count;
    }
  3. Rookje
    Member
    Posted 9 months ago #

    Thanks for your reply!

    That doesn't seem to work because it returns everything as '1', but yet I have two posts using some of those tags.

  4. Rookje
    Member
    Posted 9 months ago #

    BTW, I'm actually trying to get the tag by its slug name not the actual name.

  5. vtxyzzy
    Member
    Posted 9 months ago #

    I believe that the problem might be that more than one tag contains the text you are sending in $tag_name.

    The 'search' matches that text anywhere in the tag name. If more than one tag contains that text, you are seeing the count for only the first match.

    Try this to look for an exact match using the actual name (not the slug):

    function get_posts_count_by_tag($tag_name)
    {
        $tags = get_tags(array ('search' => $tag_name) );
        foreach ($tags as $tag) {
          if ($tag->name == $tag_name) {
             return $tag->count;
          }
        }
        return 0;
    }
  6. Rookje
    Member
    Posted 9 months ago #

    Thanks, something like what you wrote there did the trick :)

Reply

You must log in to post.

About this Topic