Wp_query post__not_in无效

时间:2016-11-28 17:53:59

标签: mysql wordpress

我尝试使用wp_query构建查询,其中必须排除某些帖子ID。以下是我使用的代码:

$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 );

但是wp_query仍然会将这些ID的帖子归还给我。

这是带有wp_query对象http://pastebin.com/gjayN4Yc的pastebin。 至于wp_query->请求我有以下内容:

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

我做错了什么或者这是一个核心错误?

谢谢。

3 个答案:

答案 0 :(得分:1)

我运行了你的代码,它对我来说很好,除了在'post__not_in '之后有一个额外的空格。你看到了吗?确保密钥为'post__not_in'

此外,还有几件事需要提及:

  1. 它是'post_type'而不是'posttype
  2. 'menu_order'不适用于帖子。这是为分层帖子类型分配的,例如pages。您在页面顺序UI中设置了该字段,该字段在默认情况下不可用于帖子。
  3. 以下是修订后的代码:

    $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();
    

    然后SQL查询变为:

    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
    

答案 1 :(得分:0)

您是否尝试在post数组键中$args之后添加第二个下划线 - 因此它post__not_in(连续2个下划线)而不是post_not_inthe WP_Query docs

答案 2 :(得分:0)

试试这个

$aTest = new WP_Query( array( 
                             'post_type'      => 'post', 
                             'posts_per_page' => -1, //all post
                             'order'          => 'ASC',
                             'cat'            => 14,
                             'post__not_in'   => array(27),
                             'orderby'        => 'date',
                             'post_status'    => 'publish'
                             ) );
while ( $aTest ->have_posts() ) : ($aTest ->the_post()) ;
$aTest Image      = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
$title            = get_the_title();
$content          = get_the_content();
endwhile;