Restrict Access to Posts based on Custom User and Post Meta Data
I have a custom Post Type called Club Pages, and a custom role called “Club Leader”. Club Leaders currently can only read, modify, and delete all Club Pages posts. However, there are many different clubs that have their own sets of pages in this post type, and I need to make sure that Club Leaders can only read, edit, and delete the pages in WP Admin that are associated with their specific club.
Currently, each Club Pages post has a custom meta data field called
club_name. I’m not using hierarchical post types to represent each club because there will be about 100 of them — all of which need to use the same template and menu, which seems like a super cluttered and unmanageable admin area for super admins. I’m not opposed to using child post types if I need to, though.
So, my plan was to add a custom User Meta field, also called
club_name, to represent which club Club Leaders are associated with, and somehow filter the Post Listing in the WP Admin to only show posts that have the same
club_name as that user. So I’m thinking the logic for this filter would be something like:
If User->Role == 'Club Leader' get `user->club_name` For each Post If `post->club_name` == `user->club_name` return `post_item` Else return nothing
I expect each Club Leader to only be associated with one club each, but bonus points your solution allows me to give a single Club Leader access to multiple clubs’ pages, in case that changes in the future.
Also, I know I only provided pseudo-code, but I’m looking for the full PHP code solution.