简体   繁体   中英

wordpress - category__not_in not working

I'm having a problem getting my query function. I need to run the loop, excluding a particular category.

I'm trying to use category__not_in , but is not working at all some.

<?php
  $args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'category__not_in' => array( '44' ),
    'posts_per_page' => 9,
    'paged' => get_query_var('paged')
  );
  $query = new WP_Query( $args );

  query_posts($query);
?>

I've already tried:

'category__not_in' => array( '44' ),
'category__not_in' => array( 44 ),
'category__not_in' => '44',
'category__not_in' => 44,

But nothing works =(

Try using tax_query instead :

<?php
  $args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 9,
    'paged' => get_query_var('paged'),
    'tax_query' => array(
        array(
            'taxonomy' => '<YOUR TAXONOMY NAME>',
            'field'    => 'term_id',
            'terms'    => array( 44 ),
            'operator' => 'NOT IN',
        ),
    ),

  );
  $query = new WP_Query( $args );

  query_posts($query);
?>

Use 'cat' => '-44' in your $args array:

$args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'cat' => '-44',
    'posts_per_page' => 9,
    'paged' => get_query_var('paged')
);

It's the way recommended in the WP Codex .

Thanks guys, it worked thanks to @rnevius

The problem was in my query, I was using WP_Query() and query_posts() .

I used how reference the WP Codex: https://codex.wordpress.org/Class_Reference/WP_Query

Below is how my code was at the end:

<?php
  $args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'category__not_in' => array( 44 ),
    'posts_per_page' => 9,
    'paged' => get_query_var('paged')
  );
  $query = new WP_Query( $args );
?>

<?php
  if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
      $query->the_post();
?>

// code

<?php
    }
  } else {
    // no posts found
  }
  wp_reset_postdata();
?>

To exclude a category in the search use this:

function search_filter($query)
{
if ( !is_admin() && $query->is_main_query() ) {
    if ($query->is_search)
    {
        $taxquery = array(
            array(
                'taxonomy'  => 'category',
                'field'     => 'term_taxonomy_id',
                'terms'     => 244,
                'operator'  => 'NOT IN',
            )
        );
        $query->set( 'tax_query', $taxquery );
    }
}

}

add_action('pre_get_posts','search_filter');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM