how to make a filter using taxonomy
I have this code below in my WP function. Filters work very well when running $ args1 or $ args2 or $ args3 or $ args4, but when together all $ args stop working.
Also I would like to integrate the filter, that is, to be able to query $ args1 and $ args3 together, or $ args1 and $ args4 or $ args1 and $ args2 and so on.
I would like a filter like this:
https://www.usf.edu.br/eventos/#conteudoInternas
Following is the code below:
//filtrar
add_action(‘wp_ajax_myfilter’, ‘filter_news’); // wp_ajax_{ACTION HERE}
add_action(‘wp_ajax_nopriv_myfilter’, ‘filter_news’);
function filter_news(){
// $args = array(
// 'post_type' => 'post',
// 'posts_per_page' => -1 ,
// 'orderby' => 'date', // we will sort posts by date
// 'order' => $_POST['date'], // ASC or DESC
// 'fields' => 'ids',
// );
$args1 = array(
'fields' => 'ids',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $_POST['areafilter'],
),
),
);
$query1 = new WP_Query( $args1 );
$args2 = array(
'fields' => 'ids',
'tax_query' => array(
array(
'taxonomy' => 'post_tag',
'field' => 'id',
'terms' => $_POST['assuntofilter'],
),
),
);
$query2 = new WP_Query( $args2 );
$args3 = array(
'fields' => 'ids',
'date_query' => array(
array(
'key' => 'mes',
'month' => $_POST['mesfilter'],
),
),
);
$query3 = new WP_Query( $args3 );
$args4 = array(
'fields' => 'ids',
'date_query' => array(
array(
// 'relation' => 'OR',
'key' => 'ano',
'year' => $_POST['anofilter'],
),
),
);
$query4 = new WP_Query( $args4 );
$all_IDs = array_merge( $query4->posts);
$final_query = new WP_Query( array( 'post__in' => $all_IDs ) );
if( $final_query->have_posts() ) :
while( $final_query->have_posts() ): $final_query->the_post();
echo '<article id="post-'. $final_query->post->ID.'" class="post-default ajax"> ';
echo '<a class="post-default__link" href="'.get_the_permalink().'">';
echo '<img class="post-default__image" src="'.get_the_post_thumbnail_url().'" />';
echo '</a>';
echo '<div class="post-default__meta post-meta">';
echo'<div class="post-meta__column">';
echo'<span class="post-meta__date">'.get_the_date().'</span>';
echo'</div>';
echo'</div>';
echo '<h2 class="h1"><a class="post-default__link" href="'.get_the_permalink().'">'.get_the_title().'</a></h2>';
echo '<p>'.the_excerpt().'</p>';
echo '<div class="post-default__footer post-footer">
<div class="post-footer__column" style="width: 42% !important;"> Área:';
echo '<p><span>'.the_category('Assunto:', '<br />').'</span>
<span> '.the_tags( ' / Assunto: ', '<br />').'</span></p>';
echo '<a href="'.get_the_permalink().'" class="post-footer__btn btn-default">saiba mais</a>
</div>';
echo '<div class="post-footer__column">
<span class="post-footer__comments">'.comments_number( '(0) Comentários', '(1) Comentário', '(%) Comentários' ).'</span>
</div>';
echo '</article>';
endwhile;
wp_reset_postdata();
else :
echo '<h1> Nenhuma notícia encontrada </h1>';
endif;
die();
}
Leave an answer