How to filter / exclude posts by id in list of posts in WordPress Dashboard / Admin

Okay, so I’ve answered my own question. Here is some code on how I did it.

function exclude_list_per_function( $query ) {

    global $wpdb;

//gets all the post ID's, I know this is a bit of a hack
    $querystr = "
        SELECT $wpdb->posts.ID
        FROM $wpdb->posts
    "; $post_ids = $wpdb->get_results($querystr, OBJECT);

        //Go through each post and pass it to a function that returns true if the user_can, and false if the user_can't
        foreach($post_ids as $post_obj){
            if(!can_user_other_function_view_this_post(get_post($post_obj->ID))){
                //if they_can't, add them to the array to be excluded
                $posts_not_in[]=$post_obj->ID;
            }
        }

        //Set those posts to be excluded from the list.
        if(is_array($posts_not_in)) $query->set( 'post__not_in', array_merge($query->get('post__not_in'), $posts_not_in) );
}

add_action( 'pre_get_posts', 'exclude_list_per_function');

From How to filter / exclude posts by id in list of posts in WordPress Dashboard / Admin

Leave a Reply