I have a custom post (it’s called “items”:wink: and 2 categories there.
1. on category page, I need to get posts which belong to 2 categories.
get posts from category1=”Food” and category2=”featured”
How can I get these posts from 2 categories?
This is what I have been doing is….
I just got posts from “FOOD” like this. at the same time, I also need to get “featured” from “cate-type2”.
I am trying 2 ways…
global $post;
$tmp_post = $post;
$args = array(
'posts_per_page' => 5,
'post_type' => 'ait-dir-item',
'category__and' => array(6, 39) // where 1, 2 is cat id
/*'tax_query' => array(
array(
'taxonomy' => 'ait-dir-item-special',
'field' => 'id',
'terms' => 39 // taxonomy id
)
)*/
);
$myposts = get_posts( $args );
foreach( $myposts as $post ) :
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
$thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail_size' );
$url = $thumb['0'];
?>
<li class="display_special_items"><img src="<? echo $url; ?>"/><a>"><?php the_title(); ?></a>
<?php endforeach; ?>
<?php $post = $tmp_post; ?>
<li class="clear">
2nd way : relation and AND
so I need to get posts from
tax1 : item-special (cate id: 6)
tax2 : item-category (cate id: 39)
$custom_terms = get_terms('ait-dir-item-special');
$other_custom_terms = get_terms('ait-dir-item-category');
foreach ($custom_terms as $custom_term) {
foreach ($other_custom_terms as $other_custom_term) {
wp_reset_query();
$args = array('post_type' => 'ait-dir-item',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'ait-dir-item-category',
'field' => 'id',
'terms' => 6
),
array(
'taxonomy' => 'ait-dir-item-special',
'field' => 'id',
'terms' => 39
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
echo '<h1 style="margin-top:10px;">'.$custom_term->name.'</h1>';
while($loop->have_posts()) : $loop->the_post();
echo '<h2><a href="'.get_permalink().'">'.get_the_title().'</a></h2>';
endwhile;
}
}
}
I think I have little problems with this code. it shows but duplicated and all item posts. how should I fix it?
Thanks,