Of course, this can be counted as a duplicate, but I can't beat this task in any way, I'm just learning)
There are several taxonomies, for example, location
and set
. I need to output the number of posts included in both taxonomies. My function now looks like this:
function get_all_property_count($id, $setid)
{
$count = new WP_Query(array(
'nopaging' => true,
'post_type' => 'property',
'post_status' => 'publish',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'location',
'field' => 'id',
'fields' => 'ids',
'terms' => $id,
),
array(
'relation' => 'AND',
array(
'taxonomy' => 'set',
'field' => 'id',
'fields' => 'ids',
'terms' => $setid,
'include_children' => true,
)
)
),
));
return $count->post_count;
}
Then I use it to get a counter of posts published in the current taxonomy and another by id (I'm not sure if I'm explaining it correctly().
<div class="count_property">
<div class="sell">
<span class="strong">Sell:</span> <?php echo get_all_property_count($term->term_id, 30); ?>
</div>
<div class="rent">
<span class="strong">Rent:</span> <?php echo get_all_property_count($term->term_id, 31); ?>
</div>
</div>
Where $term->term_id
, category id from location
taxonomy. 30
and 31
sale and rental categories from set
taxonomy.
At the exit I get one more in sell
. For example,Sell: 2
(although there should be 0 in general), Rent: 1
(that's right).
My Answer:
To get all posts that are included in both taxonomies (location and set), you need to modify your WP_Query arguments. Here's an updated version of your function:
php
function get_all_property_count($location_id, $set_id)
{
$count = new WP_Query(array(
'nopaging' => true,
'post_type' => 'property',
'post_status' => 'publish',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'location',
'field' => 'term_id',
'terms' => $location_id,
),
array(
'taxonomy' => 'set',
'field' => 'term_id',
'terms' => $set_id,
)
),
));
return $count->post_count;
}
In this updated function, we are using the 'relation' => 'AND' to make sure that the posts returned are included in both taxonomies. We are also using 'field' => 'term_id' instead of 'id' and removing the 'fields' => 'ids' argument.
You can then use this function in your template like this:
php
Sell: term_id, 30); ?>
Rent: term_id, 31); ?>
This should now correctly output the number of posts that are included in both the location and set taxonomies for the specified category IDs.
Rate this post
4 of 5 based on 5997 votesComments