I create two custom post_type. The name of the custom post is-
1. Brand
2. Ethical
And I have created a taxonomy. The name of the taxonomy is - Pharma. The common taxonomy of the two custom posts is one (pharma).
Now I want, on one page -
1. Just to display all the names of Pharma Taxonomy.
2. I would like to display only brand custom posts under Pharma Taxonomy.
3. I would like to count only the post of brand custom post under pharma taxonomy.
All right. But when I just call the brand custom post_type with Pharma Taxonomy then the ethic custom post also becomes a call. I want a solution.
$args = array(
'post_type' => 'brand',
'taxonomy' => 'pharma',
'order' => 'ASC',
'posts_per_page' => -1,
);
$query = new WP_Term_Query($args);
foreach ($query->get_terms() as $term) : ?>
<div class="item_wrap">
<h2><a href="<?php echo esc_url(get_term_link($term->term_id)); ?>"><?php echo $term->name; ?></a></h2>
<span class="count"><?php echo $term->count; ?> <?php _e('brands'); ?></span>
</div>
<?php endforeach;
WP_Term_Query
does NOT take 'post_type'
argument Here's a list of valid arguments
Docs. However, you could add a WP_Query
Docs inside your foreach
statement. Like this:
$pharm_args = array(
'taxonomy' => 'pharma',
'orderby' => 'name',
'order' => 'ASC',
);
$pharm_query = new WP_Term_Query($pharm_args);
foreach ($pharm_query->get_terms() as $term) :
$count_args = array(
'post_type' => 'brand',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => $term->taxonomy,
'field' => 'slug',
'terms' => $term->slug,
),
)
);
$count_term_in_cpt = new WP_Query($count_args);
if ($count_term_in_cpt->found_posts) {
?>
<div class='item_wrap'>
<h2><a href="<?php echo esc_url(get_term_link($term->term_id)); ?>"><?php echo $term->name; ?></a></h2>
<span class='count'><?php echo $count_term_in_cpt->found_posts; _e('brands'); ?></span>
</div>
<?php
}
wp_reset_postdata();
endforeach;
Which will output this: