<?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;
}