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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.