How to hide fields based on the current user's role

Created by Phil Kurth, Modified on Mon, 03 Jul 2023 at 10:23 AM by Phil Kurth

If you need to hide fields based on a user's role, you may do so using the af/field/before_render filter. By returning false, you can effectively prevent a field from rendering in the form as per the following example:


add_filter( 'af/field/before_render', function ( $field, $form, $args ) {

  // Check if this is the correct form
  if ( $form['key'] !== 'form_63603dfd5f7d2' ) {
    return $field;
  }

  // Get the current user role
  if ( $current_user = wp_get_current_user() ) {

    // Limit some fields to administrators only
    if ( ! in_array( 'administrator', $current_user->roles ) ) {

      // If the field key is within any of the specified, hide it
      if ( in_array( $field['key'], [ 'field_63603df414f2a', 'field_63603e7514f2b' ] ) ) {
        return false;
      }
    }
  }

  return $field;
}, 10, 3 );

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select atleast one of the reasons

Feedback sent

We appreciate your effort and will try to fix the article