post__not_in不被排除在外

时间:2017-05-01 12:24:47

标签: php wordpress

我试图在钩子pre_get_posts中使用自定义meta_key排除某些帖子,但由于某些原因无效,帖子不会被排除。要排除的分类法工作,但是帖子号

add_action('pre_get_posts' , 'changeCourseCountry');
function changeCourseCountry($query){
    global $wpdb;
    $tax_query_merge = array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'course_category',
            'field' => 'slug',
            'terms' => array('short-courses', 'mega-course'),
            'operator' => 'NOT IN'
        ),
    );
    $tax_query = array_merge($tax_query, $tax_query_merge);
    $exclude = $wpdb->get_col("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_video_course'"); // here I get an array of posts
    $query->set('tax_query' ,$tax_query);
    $query->set('post__not_in', $exlcude);
    return $query
}

1 个答案:

答案 0 :(得分:1)

请使用以下内容而不是获取列数据

$exclude = $wpdb->get_row("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_video_course'"); // here I get an array of posts 

所以它会是,

add_action('pre_get_posts' , 'changeCourseCountry');
function changeCourseCountry($query){
    global $wpdb;
    $tax_query_merge = array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'course_category',
            'field' => 'slug',
            'terms' => array('short-courses', 'mega-course'),
            'operator' => 'NOT IN'
        ),
    );
    $tax_query = array_merge($tax_query, $tax_query_merge);
    $exclude = $wpdb->get_row("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_video_course'",ARRAY_A); // here I get an array of posts
    $query->set('tax_query' ,$tax_query);
    $query->set('post__not_in', $exlcude);
    return $query;
}

此外,如果您需要多个ID,则需要使用get_results并在foreach中循环数组。

我还在$ wpdb查询中添加了ARRAY_A来检索数组。