How to show posts containing only the selected taxonomy terms in Wordpress

别来无恙 提交于 2019-12-11 17:18:10

问题


I'm trying to add a taxonomy filter form to a page using a $_GET method to push the selected taxonomy terms to the tax_query. If more terms are selected then this should return only the posts containing those exact terms. Instead I get all posts that have at least 1 of the selected terms.

This is a single array so 'relation' => 'AND' won't work here. So instead I tried setting the 'operator' parameter to 'AND' but this gives me no results at all after selecting any of the terms. I even tried pushing a foreach loop inside the query to create a new tax_query array for each term hoping to get the relation parameter to do the work instead. But this didn't work and actually seemed like a bad idea.

This is my current query setup:

get_template_part('partials/blog', 'filter');

$paged = get_query_var( 'paged', 1 );

$blog_args = array(
  'orderby' => 'date',
  'paged' => $paged,
  'posts_per_page' => 2
);
if(isset( $_GET['category'] ) ) {
  $blog_args['tax_query'] = array(
    'relation' => 'AND',
      array(
        'taxonomy' => 'category',
        'field' => 'slug',
        'terms' => $_GET['category'],
        'operator' => 'AND'
      ),
  );
}

$blog_query = new WP_Query($blog_args);

If a category is selected by the user that value get pushed to 'terms' as an array.

I expected the 'operator' parameter to act like the 'relation' parameter but this doesn't seem to be the case or am I doing something wrong?

来源:https://stackoverflow.com/questions/55981213/how-to-show-posts-containing-only-the-selected-taxonomy-terms-in-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!