Customizer JS API: Defining control settings

I am trying to create Customizer controls using JS API. What is a proper way to define control settings?

Here is my current code:

var mySetting = new api.Setting( 'section_title', 'Hello World!' );
api.add( mySetting );

api.control.add( new api.Control( 'section_title', {
  type: 'text',
  section: 'custom-section',
  setting: mySetting,
  label: 'Enter your custom title'
} ) );

When I try to save my changes, the Customizer shows an error: “Setting does not exist or is unrecognized.”

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Settings must be registered in PHP one way or another. If you don’t register them statically via $wp_customize->add_setting() calls, you will have to register dynamic recognition of them via the customize_dynamic_setting_args filter. Why? In order for a setting to be safely stored it must be sanitized and validated by the server. Relying on client-side sanitization and validation is dangerous. Additionally, the Customizer setting is what gets persisted into the DB and actually applies a change to the site. This means that WordPress needs to know what a setting is for, how to preview it, and how to save it. So you may freely create settings in JS, but you must create a
customize_dynamic_setting_args filter. You use this filter to match a given setting ID against a certain pattern you define. Examples of this can be found in core for widgets and nav menu items.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x