In a similar use case scenario, I had a client with 5 locations which could be assigned to the user. This will need to be changed for you because it’s based on location being assigned to both a user and a post, whereas you’re just going to assigning entire posts to users rather than matching post meta.
function filter_by_user_club( $query ) {
if( is_admin() ) {
$user_id = get_current_user_id();
$user_location = get_user_meta( $user_id, 'myplugin_user_location', true );
$currentscreen = get_current_screen();
if ( $currentscreen->post_type == 'custom_post_type' ) {
if( !empty( $user_location ) ) {
$location_meta_query = array(
'key' => 'cpt_location',
'value' => $user_location,
'compare' => 'IN'
);
$query->set('meta_query', array( $location_meta_query ) );
}
}
}
add_action( 'pre_get_posts', 'filter_by_user_club', 9998 );
I’m guessing that this sort of modification would need to be applied for your method, if I’m understanding your structure correctly…
You would need to change the meta_query
to instead query an array of IDs using post_in
, like so:
function filter_by_user_club( $query ) {
if( is_admin() ) {
$user_id = get_current_user_id();
$user_clubs = get_user_meta( $user_id, 'myplugin_user_clubs', true );
$currentscreen = get_current_screen();
if ( $currentscreen->post_type == 'club_post_type' ) {
if( !empty( $user_clubs ) ) {
//if you've saved the user club IDs as an array (recommended)
$query->set('post_in', $user_clubs );
//if you've saved the user club IDs as a string use this...
//$query->set('post_in', array( $user_clubs ) );
}
}
}
add_action( 'pre_get_posts', 'filter_by_user_club', 9998 );
Obviously a lot still to do to get the club IDs associated with the user, etc. but this will filter the club post type list based on the user.
We’re using $query->set()
and essentially adding an argument into that screen’s default get_posts()
query. While the query here, by default, will grab all of the posts (paginated based on how many you set per screen), we’re now telling it to only show posts_in
the array we provided when we checked which clubs a user has associated with them.