0

I have a customizer RadioControl with 3 choices: menu-left, menu-right, menu-top. I want the chosen setting to be added to the body as a class, while the others are removed.

Example

<body class="class1 menu-left"> will become <body class="class1 menu-right">

In order to do that, I want to read the choices dynamically in preview. Yet, the wp.customize.control does not work in a script enqueued in customize_preview_init-action.

I would love to:

const choices = Object.keys(wp.customize( controlKey ).params.choices).join(" ");

How can I read a controls available choices in preview?

1 Answer 1

0

Because this is for a class, and you need to remove the old value and add the new value, you need to send that information to the preview. I used a bunch of checkboxes, but it would be the same problem for radio inputs or a select. Knowing just the new value isn't enough.

I wrote javascript for my control for the control pane that initialized the control with a field that contained all the possible values (sent as json in PHP). Then each time the user chooses, the value of the setting is updated to contain the off values, a separator, and the on values. Since I was doing this for classes also, I just used a comma.

Then in the preview script, the single value is split on the separator and the off ones are used with removeClass() and the on ones are used with addClass().

You can see the full code here: https://wordpress.org/themes/twenty8teen

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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