Is it possible to conditionally displaying and hiding of customizer controls for each device preview?

I’m not familiar working with Kikri, but I’ve made a standalone example plugin that shows the approach I’d use to get controls to be contextual based on the previewed device.

The plugin adds colored outlines around each element in the site, with a different color for elements in desktop, tablet, and mobile (obviously just for demonstration purposes). There are then color controls specific to each device, and only the device for the current previewed device is shown at a given time.

The key logic in the plugin is found in wpse-286268-controls.js:

_.each( component.deviceControls, function( controlId, deviceSlug ) {
    api.control( controlId, function( control ) {
        function isActive() {
            return deviceSlug === api.state( 'previewedDevice' ).get();
        }

        // Set initial active state.
        control.active.set( isActive );

        // Update active state whenever previewd device changes.
        api.state( 'previewedDevice' ).bind( function() {
            control.active.set( isActive );
        } );

        // Override whatever the active_callback may send from server when preview loads.
        control.active.validate = isActive;
    } );
} );

The isActive function returns whether the control should be active according to the current previewed device, and then this function is used to set each control’s active state, and then each control’s active state is updated when the previewedDevice state changes. Lastly, since these controls are registered with PHP, we override the validate method to prevent the active_callback for the control from overriding the active state we set in JS (whenever the preview refreshes the active_callback for the control will be called on the server and sent back when the preview refreshes to update the active state).

Leave a Comment