PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

[FIXED] How to get the number of posts that located in 2 specific categories at the same time in WordPress

 July 08, 2022     categories, count, posts, wordpress     No comments   

Issue

I have tried to use this code:

$terms = get_terms('translates_category', 'include=220,238');

But it returns an array with two separate objects:

Array
(
[0] => stdClass Object
    (
        [term_id] => 220
        [name] => Degrees of comparison
        [slug] => degrees-of-comparison
        [term_group] => 0
        [term_taxonomy_id] => 272
        [taxonomy] => translates_category
        [description] => 
        [parent] => 217
        [count] => 2
    )

[1] => stdClass Object
    (
        [term_id] => 238
        [name] => Lesson
        [slug] => lesson
        [term_group] => 0
        [term_taxonomy_id] => 290
        [taxonomy] => translates_category
        [description] => 
        [parent] => 0
        [count] => 1
    )
)

As I can assume, it's returns number of all posts (count) in those 2 categories separately. But I need the total number of only the posts that located in both categories at the same time.

There may be 100 posts in first category and 10 in second but only 1 of them may be associated with both of categories at a time. And I need to count such posts.

How can I do that?


Solution

This should solve your problem:

function my_post_count($tax, $cat1, $cat2) {
    $args = array(
        'tax_query' => array(
            'relation' => 'AND',
            array(
                'taxonomy' => $tax,
                'field' => 'term_taxonomy_id',
                'terms' => array( $cat1 ),
                'operator' => 'IN'
            ),
            array(
                'taxonomy' => $tax,
                'field' => 'term_taxonomy_id',
                'terms' => array( $cat2 ),
                'operator' => 'IN'
            ),
        )
    );
    $query = new WP_Query( $args );
    return $query->post_count;
}
echo my_post_count('translates_category', 220, 238);


Answered By - Octav
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing