Support

Account

Home Forums Backend Issues (wp-admin) PHP Unrequire Field

Solved

PHP Unrequire Field

  • I am trying to unrequire fields for specific user roles. If the user can edit posts then this specific profile field should not be required but optional. I thought it worked but when I submit the update profile form I get the requirement pop-up.

    I’ve tried prepare_field and load_field but both hooks still tell me the field is required on submit:

    /**
     * Make some fields not required for specific users
     * 
     * @param Array $field
     * 
     * @return Array $field
     */
    function theme_acf_nonrequired_fields( $field ) {
    	
    	global $pagenow;
    	
    	if( ! is_admin() || ! current_user_can( 'edit_posts' ) ) {
    		return $field;
    	}
    	
    	if( ! in_array( $pagenow, array( 'user-new.php', 'user-edit.php', 'profile.php' ) ) ) {
    		return $field;
    	}
    	
    	$field['required'] = 0;
    	
    	return $field;
    	
    }
    add_filter( 'acf/prepare_field/name=cust_name', 'theme_acf_nonrequired_fields' );

    Is this possible or am I missing something with my hooks?

  • So the validation is run on admin-ajax.php which invalidate the $pagenow. Maybe there’s a better way to do this but I just made 2 arrays to check against both the global and the referrer.

    Open to way to make the below and above better

    /**
     * Ensure our particular fields pass validation
     * 
     * @param Boolean $valid
     * 
     * @return Boolean $valid
     */
    function theme_acf_nonrequired_fields_validate( $valid ) {
    	
    	global $pagenow;
    	
    	$acceptable_pagenows = array( 'user-new.php', 'user-edit.php', 'profile.php' );
    	$acceptable_referers = array( '/wp-admin/user-new.php', '/wp-admin/user-edit.php', '/wp-admin/profile.php' );
    	
    	if( ! is_admin() || ! current_user_can( 'edit_posts' ) ) {
    		return $valid;
    	}
    	
    	if( ! ( in_array( $pagenow, $acceptable_pagenows ) ||
    		  ( isset( $_REQUEST, $_REQUEST['_wp_http_referer'] ) && in_array( $_REQUEST['_wp_http_referer'], $acceptable_referers ) ) )
    	) {
    		return $valid;
    	}
    	
    	return true;
    	
    }
    add_filter( 'acf/validate_value/name=cust_name', 		'theme_acf_nonrequired_fields_validate' );
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘PHP Unrequire Field’ is closed to new replies.