将jquery和自定义脚本添加到WordPress主题

通过谷歌进行一些搜索,我偶然发现了相同的代码,将jQuery添加到一个从头开始的Wordpress主题。

if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11); function my_jquery_enqueue() { wp_deregister_script('jquery'); wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null); wp_enqueue_script('jquery'); wp_enqueue_script('my_script', get_bloginfo('template_url') . '/js/theme.js', array('jquery'), '1.0', true); } 

我已将此代码添加到我的functions.php文件中,并创建了一个js文件夹,并使用以下语法创建了一个theme.js文件:

 jQuery(function ($) { /* You can safely use $ in this code block to reference jQuery */ }); 

当我刷新我的WP站点时,似乎没有调用theme.js文件。 在Chrome Dev工具中,它没有列在正在呈现的js文件中。

我使用过时的方法吗? 如何使用jquery创建我的/js/theme.js文件,为我的主题工作?

首先, wp_enqueue_scripts仅在前端运行,因此您不需要进行is_admin()检查。

其次, 如果您真的知道自己在做什么 ,只能取消注册默认的jQuery(与WP捆绑在一起)。 在您的示例中,您要从Google加载过时的版本(当前为1.8.3,而不是1.7.1)。 另请参阅: 不要将WordPress的jQuery出列

第三,你应该使用get_stylesheet_directory_uri ,这是正确的function,将计算父和子主题文件夹。

最后,这段代码在/themes/my-theme/functions.php正常/themes/my-theme/functions.php

 add_action( "wp_enqueue_scripts", "my_js_so_14864221", 11 ); function my_js_so_14864221() { wp_enqueue_script( 'my_script', get_stylesheet_directory_uri() . '/js/theme.js', array( 'jquery' ), '1.0', true ); } 

并且你的theme.js中的jQuery代码应该被封装为:

 jQuery(document).ready(function($) { // $('#your-stuff').animate().hide().whatever(); });