Use posts_where to exclude posts ids from wp_query

I want to use posts_where to exclude an array of posts ids from all queries in my site.

The array containing the posts ids depends on the user that is logged in.

Can someone please tell me how to use the filter posts_where to exclude a list of posts ids from all queries in my site?

Thank you.

Topic posts-where exclude wp-query posts Wordpress

Category Web


Instead of using posts_where it is a better idea to use pre_get_posts filter. Here is the code I end up implementing:

add_filter( 'pre_get_posts', 'hide_unwanted_posts_filter' );
function hide_unwanted_posts_filter( $query ) {
    global $current_user;
    get_currentuserinfo();
    $user_id = $current_user->ID;
    $key = 'unwanted_posts';
    $unwanted_posts = get_user_meta($user_id,$key,true);
    if(is_user_logged_in() && !empty($unwanted_posts) && !$query->is_admin) {
        $query->set('post__not_in', $unwanted_posts ); // id of page or post 21753
    }
    return $query;
}

If someone reads this and still wants to use the posts_where filter. Here is the same code (simplified) using this other filter:

add_filter( 'posts_where','hide_unwanted_posts_filter', 1, 2 );
function hide_unwanted_posts_filter($where, $wp_query = NULL) {
    global $wpdb;
    $wp_posts = $wpdb->prefix . "posts";
    if ( !$wp_query ) {
        global $wp_query;
    }
    if (is_user_logged_in() && !$wp_query->is_admin) {
        $where .= " AND $wp_posts.ID NOT IN (22, 3)";
    }

    return $where;
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.