You should seriously consider managing who does what by capability instead of role. Capabilities give you finer control over what users are able to do. Think of roles as only a collection of certain capabilities. You could then possibly create a custom capability that is assigned only to one role, even a lowly subscriber. It could be something even admins couldn’t do because they were not assigned that capability. But capabilities can be assigned to users as well as roles. Perhaps two admin users would be assigned this capability, the remaining Admins would not have that capability.
An extreme, unlikely scenario for sure, but it illustrates the great flexibility of using capabilities. Since you have had roles in mind, you may simply pick a capability that the desired role has, that other roles do not. While it’s best if the capability related to the task you are managing, it really can be any that meets your criteria. There is a fairly extensive list of which roles have what capabilities. Let’s use “edit_posts” for example. Everyone but subscribers have this capability, but only admins have the “customize” capability.
You then verify the current user can do something like so: if ( current_user_can('edit_posts')) do_something();
To allow most users to do something only for certain properties that have a meta value set, but allow admins full access to all posts, use a complex logic statement. For logical operators at the same level, they are evaluated from left to right. To be safe, it’s a good idea to use parenthesis to explicitly delimit which comparisons to do first.
if (( current_user_can('edit_posts')
&& get_post_meta( $property_id, 'REAL_HOMES_agent_display_option', true )
) || current_user_can('customize')
) {
update_post_meta( $property_id, 'REAL_HOMES_agents', $_POST['agent_id']);
}
You can negate any particular logical result by preceding the clause with the NOT operator: !
. It’s commonly used to prevent the rest of some code from running unless the user has the right capability.
if ( ! current_user_can('customize')) break; //bail if user cannot customize
customize_something();
Be careful mixing NOTs, ANDs, & ORs, the logical result can be very confusing! Some phrases in English sound correct using “not” with “and” in order to decide something, but with boolean the same thing requires OR logic, not AND.