Wp_query post__not_in not working

16,968

I ran your code and it worked fine for me, except there is an extra space after 'post__not_in '. Do you see it? Make sure you have the key as 'post__not_in'.

Also, there are a couple of things to mention:

  1. It's 'post_type' and not 'posttype.
  2. 'menu_order' is not available for posts. That is allocated for hierarchical post types, such as pages. You set that field in the Page Order UI, which is not available (by default) to posts.

Here is the revised code:

$args  = array(
    'post_type'      => 'post',
    'posts_per_page' => 1,
    'cat'            => 14,
    'post__not_in'   => array( 71, 1 ),
    'orderby'        => 'date',
    'order'          => 'ASC',
    'post_status'    => 'publish',
);
$the_query = new WP_Query( $args );
if ( ! $the_query->have_posts() ) {
    // maybe echo a message that none were found
    return;
}

while( $the_query->have_posts() ) {
    $the_query->the_post();

    // do your business logic here

    // then call the view file to render the HTML
}
wp_reset_postdata();

The SQL query then becomes:

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID 
FROM wp_posts  
LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) 
WHERE 1=1  AND wp_posts.ID NOT IN (71,1) AND 
           ( wp_term_relationships.term_taxonomy_id IN (14) ) AND 
            wp_posts.post_type = 'post' AND 
            ((wp_posts.post_status = 'publish'))
GROUP BY wp_posts.ID 
ORDER BY wp_posts.post_date ASC LIMIT 0, 1
Share:
16,968

Related videos on Youtube

Ângelo
Author by

Ângelo

Updated on June 13, 2022

Comments

  • Ângelo
    Ângelo almost 2 years

    I'm trying to build a query using wp_query where certain posts id must be excluded. Here is the code that i'm using:

    $args = array( 'posttype' => 'post', 'posts_per_page' => 1, 'cat' => 14, 'post__not_in ' => array(71,1), 'orderby' => 'menu_order', 'order' => 'ASC' , 'post_status' => 'publish' );
    $the_query = new \WP_Query( $args );
    

    However wp_query is still returning me the posts with those ID's.

    Here is the pastebin with the wp_query object http://pastebin.com/gjayN4Yc. As for the wp_query->request i'm having the following:

    SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (14,15) ) AND wp_posts.post_type = 'post' AND ((wp_posts.post_status = 'publish')) GROUP BY wp_posts.ID ORDER BY wp_posts.menu_order ASC LIMIT 0, 3
    

    Am i doing something wrong or is this a core bug?

    Thank you.

  • Ângelo
    Ângelo over 7 years
    Hello, somehow while pasting it came up wrong but in the source code was just like you said.