Ideally entry controls can be carried out through WordPress’s Roles and Capabilities system. However in highly-granular instances similar to limiting entry to a single publish to some customers, the map_meta_cap
filter can be utilized to shim in further restrictions.
On this case, when WordPress is testing an edit_post
functionality for a consumer/publish mixture, we are able to deny entry based mostly in your customized meta subject:
perform wpse406371_restrict_affiliate_page_edit( $caps, $cap, $user_id, $args ) {
if( $cap !== 'edit_post' )
return $caps;
$post_id = $args[0];
if( get_post_type( $post_id ) !== 'affiliate' )
return $caps;
$affiliate = get_field( 'field_627ff399b5ef6', 'user_' . $user_id );
if( empty( $affiliate ) )
return $caps;
$affiliate_page_id = $affiliate[0]->ID;
if( $post_id == $affiliate_page_id )
return $caps;
$affiliate_child_page_ids = get_children([
'post_type' => 'affiliate',
'post_parent' => $affiliate_page_id,
'fields' => 'ids',
]);
if( !in_array( $post_id, $affiliate_child_page_ids ) )
$caps[] = 'do_not_allow';
return $caps;
}
add_action( 'map_meta_cap', 'wpse406371_restrict_affiliate_page_edit', 10, 4 );
The above can be executed each time WordPress exams a consumer’s capabilities for an motion. Within the instances that the aptitude examine isn’t for enhancing a publish, the publish isn’t an affiliate
-type, or the consumer doesn’t have field_627ff399b5ef6
meta-data, the examine will return the unmodified capabilities early to be able to mitigate further work.
Checking if the publish being edited is the father or mother affiliate
publish is carried out early to be able to skip the publish question if doable.
I’ve additionally added the 'fields' => 'ids'
argument to the kid web page question to avoid wasting on overhead by solely retrieving publish IDs as an alternative of querying full rows – however I nonetheless really feel this might be an overly-expensive operation on a capabilities examine. You would possibly think about caching the publish IDs in consumer meta someday sooner or later must you decide that the question provides notable overhead.
Lastly, if the present publish’s ID isn’t current within the queried ID listing, the perform provides the do_not_allow
functionality which is able to natively deny the consumer entry. This may impact all core strategies of enhancing a publish – the Fast Edit type, through REST API, and so forth.