I am developing a WordPress theme and I am working on the theme customizer for the theme options. I want to validate the inputs and to show an alert if the validation fails in the theme customizer.
This is what I have tried
$wp_customize->add_setting('custom_social_settings[facebook]',array(
'default' => '',
'type' => 'option',
'sanitize_js_callback' => 'check_url'
));
function check_url(){
?>
<script>
jQuery(document).ready(function(){
// My validation script
});
</script>
<?php
}
The problem is when I load the page sanitize_js_callback gets executed twice. When will be the sanitize_js_callback
will be invoked? It should be invoked only when I click the save button. Should I write script for the click event of the save button. Is there any better way to do validation in WordPress theme customizer? How to do a typical form validation in WordPress theme customizer?
Thanks in advance
You should use customize_register hook and it shouldn’t run twice because those callbacks (including
sanitize_callback
) should be executed (bound to) only when you save your data/submit the form. Well, if you are doing it using the hook and still now you are facing this problem then I think (maybe not best) you can check if the form is submitted or not (isset($_post['submit'])
).To sanitize a
url
(before saving in database) you can use esc_url_raw function. Check Data Validation and this nice tutorial.