Conditionally Show an ACF Field based on a Field in another Field Group

This is more of a tip than a tutorial, but handy as always!

ACF is coming out with more powerful conditional logic, which is awesome! I don’t know yet ALL of what it will include — but in the meantime, have you ever wanted to conditionally show an ACF field in the admin based on another field in a different field group?

I have wanted to. In fact, I just finished doing that for a client. So naturally, I thought why not write up a little tutorial about it?

Here’s our example scenario:

We want show a field on the Add/Edit User Profile screen based on which User Roles are selected in Theme Options. I’m using an ACF add-on to create a Role Field, but other than that, all you need is ACF and your handy dandy code editor.

First we’re going to create our respective fields:

Here we’ve got an Options field group with a User Role field (this screenshot is from a real website we’ve worked on).

In this field group, we’ve got an example field and we’ve assigned it to the Add/Edit User screen.

Make sure the field keys are visible (Screen Options > Field Keys), and now grab the Field Key of the field on the Add/Edit User Screen.

We’re going to be using the load_field filter to affect the visibility of the example field. We’ll hook in a function that checks the role of the user who’s Add/Edit screen we’re viewing, and then cross-reference that with the other field where we’ve selected user roles.

<?php

add_filter('acf/load_field/key=field_5a6104c98687a', 'example_field_visbility');

function example_field_visbility ($field) {
    // this global variable is available to us on the add/edit user screen
    global $user_id;

    // we're going to use the user_id to grab the User object group which will have their role(s) listed in it    
    $user = get_user_by( 'ID', $user_id);
    $user_role = $user->roles;

    // now we're going to grab our Theme Options field that has all the roles and grab the roles array for it
    $roles_with_files = get_field('roles_with_files', 'option');
    $roles_allowed = $roles_with_files['roles'];
    
    // if the user role is in the $roles_allowed array, allow the field to be returned (aka shown), 
    // otherwise, don't return the field, which means it won't appear
    if ( (in_array( $user_role[0], (array) $roles_allowed )) ) {
        return $field;
    }
}

Wasn’t that easy?

We’re creating a(n opinionated) course on WordPress Theme Development!

It’s going to be jam-packed (over 35k words!) and full of awesome information for a budding WordPress theme developer. If you’d like to hear more about it, pop in your email address.

Awesome! We’ll send you updates and sneak peeks of the course! Plus, whenever we publish other handy tutorials, we’ll be sure to let you know. No spam, we promise.

It looks like you're already subscribed. Yay!