I am trying to exclude some posts with a custom meta_key within the hook pre_get_posts
but for some reason is not working, the posts are not getting excluded. Taxonomies to be excluded work, but posts no.
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
}
Please use the following instead of getting the column data,
$exclude = $wpdb->get_row("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_video_course'"); // here I get an array of posts
So it will be ,
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;
}
Also if you need multiple IDs then you need to use get_results
and loop the array in foreach.
I also added ARRAY_A to $wpdb query to retrive the array.