0

I try to dynamically add settings, sections, and controls to the customizer. With the help of this question and Weston’s answer I made it already so far, that I can add a control and setting via the JS api that gets saved to the database. My problem is, that after reloading the customizer, the control field is empty.

This is the JS code:

var setting = new wp.customize.Setting( 'portfolio_category_page' );
wp.customize.add( setting );

// Add control to select the category to show on the page.
wp.customize.control.add(
    new wp.customize.Control('portfolio_category_page', {
        setting: setting,
        type: 'text',
        section: 'hannover_portfolio_category_page',
        label: 'Choose page',
    })
);

And the current function which gets hooked to the customize_dynamic_settings_args filter:

function hannover_filter_dynamic_setting_args( $setting_args, $setting_id ) {
    if ( 'portfolio_category_page' === $setting_id ) {
        $setting_args = array(
            'type' => 'theme_mod',
        );
    }
    return $setting_args;
}

Like said, after saving the customizer changes, I see the portfolio_category_page theme mod in the database, but after reloading the Customizer, the text field is empty…

Is there some step I missed?

Thanks in advance!

1

The field is empty because when you create it in JS you are not providing it a value as the second parameter when constructing the Setting. You'd have to obtain it with a REST API call presumably here.

Take this example from the Customize Comments plugin:

setting = new api.Setting( customizeId, comment.content.raw, {
    transport: 'postMessage'
} );
api.add( setting );

You can see in the plugin how it is fetching comments from the REST API.

But why use a dynamic setting here? This seems like it should be registered statically since it appears to be a one off.

  • Thanks Weston, will try that out! I use a dynamic setting because it should be possible to add/remove category pages via the customizer, similar to the workflow with the menus in the customizer. – Florian Brinkmann Dec 13 '17 at 7:04
  • I updated my answer to include some examples. – Weston Ruter Dec 13 '17 at 7:19
  • Great, thanks a lot! With that, I should get it working. – Florian Brinkmann Dec 13 '17 at 7:23

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.