首页 > 解决方案 > 无法让 jquery datepicker 在 Wordpress 插件中工作

问题描述

我是 jquery 和 php 的新手,正在尝试创建我的第一个 Wordpress 插件。该插件只是在后端有一个日期字段的帖子中添加一个元框。

Metabox 和字段都添加好了,并在我创建或编辑帖子时出现。

但是,我无法让日期选择器工作。单击输入框时没有任何反应,日期选择器不显示。虽然输入框只会让我输入数字而不是字母。

该插件是一页php代码。

我的插件文件的顶部尝试加载 jquery:

function ca_load_jquery_datepicker() { 
    wp_enqueue_script('jquery-ui-datepicker');
    wp_enqueue_style('jquery-style', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css');
}
add_action( 'admin_enqueue_scripts', 'ca_load_jquery_datepicker' );

然后这是我表单中的输入和 jquery(在插件文件的下方):

<input type="text" class="date" name="ca_expiry_date" value="">

        <script type="text/javascript">
            jQuery(document).ready(function($) {
                $('.date').datepicker({
                    dateFormat : 'yy-mm-dd'
                });
            });
        </script> 

谁能帮忙告诉我日期选择器哪里出错了?谢谢!

更新

感谢您的评论,我发现如果我安装“经典编辑器”插件,我的代码就可以工作。但是,当它没有被激活并使用古腾堡时,它就不起作用了。

错误是(不共享网站网址):GET https://xxxx.co.uk/wp-content/themes/publisher/gutenberg-7.6.2.min.css?ver=7.6.2 net::ERR_ABORTED 404 (未找到)

即使我的插件被禁用,这个错误仍然存​​在。

但是,如果我激活了 29 主题,则没有错误,但我的插件中的日期字段仍然不起作用。

很明显,古腾堡不喜欢我的代码中的某些内容......

标签: phpjquerywordpress

解决方案


我会确保从functions.php您当前主题的远程官方来源注册整个 jquery-ui 包,如下所示:

function ca_load_jquery_ui() {
    // first, register the style from the remote official source
    wp_register_style('jqueryuicss', '//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.min.css', array('jquery-ui-styles'), '1.12.1');
    wp_enqueue_style('jqueryuicss');
    // then, register the core file from the remote official source, in footer
    wp_register_script('jqueryui', '//code.jquery.com/ui/1.12.1/jquery-ui.min.js', array('jquery-ui'), '1.12.1', true);
    wp_enqueue_script('jqueryui');
}
add_action( 'wp_enqueue_scripts', 'ca_load_jquery_ui' );

注意:如果您想在前端使用日历,请确保使用该功能add_action( 'wp_enqueue_scripts', 'xxx' );,而不是add_action( 'admin_enqueue_scripts', 'xxx' );仅适用于管理员端。


更新

您也可以尝试禁用默认的 jQuery 或 jQuery-ui 以查看是否有帮助:

//remove the default jQuery script
function remove_default_jquery(&$scripts){
    if(is_admin()){
        // try this...
        $scripts->remove('jquery');
        // or...
        $scripts->remove('jquery-ui');
    }
}
add_filter( 'wp_default_scripts', 'remove_default_jquery' );

推荐阅读