Support » Fixing WordPress » Count number of posts with a specified tag AND category

  • Resolved catsfoto1se

    (@catsfoto1se)


    With this php snippet I can see how many posts that have the tag “cat

    $term = get_term_by('slug', cat, post_tag);
    $nocats = $term->count;

    But how do I do if I want to count how many of those cats that are in the category allowpost?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Please try the following code:

    $args = array(
      'posts_per_page' => -1,
      'tax_query' => array(
        'relation' => 'AND', // only posts that have both taxonomies will return.
        array(
          'taxonomy' => 'post_tag',
          'field'    => 'slug',
          'terms'    => 'your-tag-slug', //cat
        ),
        array(
          'taxonomy' => 'category',
          'field'    => 'slug',
          'terms'    => 'your-category-slug', //allowpost
        ),
      ),
    );
    $posts = get_posts($args);
    $count = count($posts);

    Basically in the code, we are checking if the posts are in both the taxonomies then send them in the output and then counting the total of them.

    I hope this will help you.

    Thread Starter catsfoto1se

    (@catsfoto1se)

    @prashantvatsh Thank you so much, it works perfect!

    I would never have gotten that script together, thx again!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Count number of posts with a specified tag AND category’ is closed to new replies.