Show or Hide Fields Based On Role

Support MB Conditional Logic Show or Hide Fields Based On RoleResolved

Viewing 4 posts - 16 through 19 (of 19 total)
  • Author
    Posts
  • #44293
    sododesignsododesign
    Participant

    I created a custom function to achieve this. It also works with group or sub-nested fields

    <iframe src="https://pastebin.com/embed_iframe/5gnE8PL9" style="border:none;width:100%"></iframe>

    #44294
    sododesignsododesign
    Participant
    
    <?php
    // CREATE CUSTOM FUNCTIONS FOR RESTRICT FIELDS
    function cmb_fields_by_user_role( $fields ) {
        $current_user = wp_get_current_user();
        $user_roles   = $current_user->roles;
    
        $filtered_fields = array_filter($fields, function($field) use ($user_roles) {
            // If the field does not have the 'cmb_role' key, we include it by default
            if (!isset($field['cmb_role'])) {
                return true;
            }
    
            // Checks if one of the user's roles is in 'cmb_role'
            foreach ($user_roles as $role) {
                if (in_array($role, $field['cmb_role'])) {
                    return true;
                }
            }
    
            return false;
        });
    
        return array_values($filtered_fields); // Reindex array
    }
    
    // EXAMPLE METABOX FIELDS
    add_filter( 'rwmb_meta_boxes', 'register_example_fields' );
    function register_example_fields( $meta_boxes ) {
    	$meta_boxes[] = [
            'title'        => __('Custom Metabox'),
            'id'           => 'custom-metabox',
            'post_types'   => ['cpt'], // CPT
            'fields'       => cmb_fields_by_user_role([
                [
                    'type' => 'text',
                    'id'   => 'field_1',
                    'name' => '<h3>Field 1</h3>',
    				'cmb_role   => array(administrator')
                ],
                [
                    'type' => 'text',
                    'id'   => 'field_2',
                    'name' => '<h3>Field 2</h3>',
    				'cmb_role   => array('author','administrator')
                ],
                [
                    'type' => 'text',
    				'id'   => 'field_3',
                    'name' => '<h3>Field 3</h3>',
    				'cmb_role   => array('administrator')
                ],
            ])
        ];
    
        return $meta_boxes;
    }
    
    #46101
    JoeJoe
    Participant

    any news on this ?

    #47217
    brkardbrkard
    Participant

    +1000
    still waiting..

Viewing 4 posts - 16 through 19 (of 19 total)
  • You must be logged in to reply to this topic.