0

Is it possible to limit the selection of a specific customizer option to user roles?

Right now I have this custom control:

$wp_customize->add_control( 'checkin[theme]', array(
'label' => __('Theme', 'greet'),
// 'description' => 'Set theme',
'section' => 'checkin',
'type' => 'select',
'choices'  => array(
        'theme-1' => 'Background',
        'theme-2' => 'Stars (Live)',
        'theme-3' => 'Gradient (Live)',
    ),
) );

I would like to limit the theme-2 and theme-3 to only be available for a specific user role, and either be unavailable or greyed out/disabled for the other roles.

How do I do this with an array?

0

There are 2 ways to do this.

  1. When registering a setting you can use the capability:
$wp_customize->add_setting(
    'display_excerpt_or_full_post',
    array(
        'capability'        => 'edit_theme_options',
        'default'           => 'excerpt',
        'sanitize_callback' => function( $value ) {
            return 'excerpt' === $value || 'full' === $value ? $value : 'excerpt';
        },
    )
);
  1. When registering the control, you can use the render_callback argument to determine if the control will be shown or not:
$wp_customize->add_control( 'checkin[theme]', array(
    'label' => __('Theme', 'greet'),
    'section' => 'checkin',
    'type' => 'select',
    'choices'  => array(
            'theme-1' => 'Background',
            'theme-2' => 'Stars (Live)',
            'theme-3' => 'Gradient (Live)',
        ),
    ),
    'render_callback' => function() {
        return current_user_can( 'edit_posts' );
    },
);

Please note that these are completely different. Using the capability argument in the setting will skip the control altogether and it will not be added to the customizer API. Using the render_callback argument, the control will still be added in the customizer and it will be available from the API, it will just be hidden. If hidden (but still exposed in the API) I can open the console and do this to show it - even though you've hidden it:

wp.customize.control( 'checkin[theme]' ).activate()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.