Saving Default Value for WordPress Customizer Setting

While using WordPress customizer api I got confused with how default value parameter is handled by setting. As I realised that setting do not save default value in database and instead one is supposed to use default parameter for get_theme_mod. I personally found it difficult to provide default value parameter multiple times as part of get_theme_mod call. So, I wrote little extra code to save the default values in database.

Here is an example code for a customizer setting that let user choose between two blog layouts. The default value for setting id ‘inspiry_post_layout’ is ‘one’ in this example.

To save a default value I created this helper function. Which only saves a default value for a setting in database, If it does not exist already.

Now, To connect this helper function with setting declared in above example and to call it at right time I wrote the following function and hooked it with ‘customize_save_after’ action hook.

For Type Option

If you are using setting of type ‘option’ instead of ‘theme_mod’ then you can replace helper function code given above with following code.

I hope above given code examples will help you with your project.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *