2

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

4

1 回答 1

3

您应该使用customize_register钩子,它不应该运行两次,因为这些回调(包括sanitize_callback)只有在您保存数据/提交表单时才应该执行(绑定到)。好吧,如果您使用钩子进行操作,但现在您仍然面临这个问题,那么我认为(也许不是最好的)您可以检查表单是否已提交(isset($_post['submit']))。

要清理url(在保存到数据库之前),您可以使用esc_url_raw函数。检查数据验证这个不错的教程

于 2013-08-01T05:15:59.490 回答