2012-05-26 40 views
0

好了,这是我functions.php文件:我该如何使用wp_enqueue_script?

function mdg_setup_scripts() { 
    wp_register_script('hoverIntent', get_bloginfo('template_url').'/js-custom/hoverIntent.js', array('jquery')); 
    wp_enqueue_script('hoverIntent'); 
    wp_register_script('mdMenuAnimation', get_bloginfo('template_url').'/js-custom/mdMenuAnimation.js', array('jquery')); 
    wp_enqueue_script('mdMenuAnimation'); 
} 
add_action('wp_enqueue_scripts', 'mdg_setup_scripts'); 

这是我本来有:(被编辑过的版本,利用下面冷静的回答,我离开原来的事后以下

function mdg_setup_scripts() { 
    wp_register_script('hoverIntent', 
    get_bloginfo('template_url') . '/js/hoverIntent.js', 
    array('jquery'), 
    false, 
    true); 
    wp_register_script('mdMenuAnimation', 
    get_bloginfo('template_url') . '/js/mdMenuAnimation.js', 
    array('jquery', 'hoverIntent'), 
    false, 
    false); 
    if (!is_admin()) { 
    wp_enqueue_script('mdMenuAnimation'); 
    } 
} 
add_action('init', 'mdg_setup_scripts'); 

的js文件存在于指定的文件夹中。 但根本没有的JavaScript加载在前端。 我做错了什么,但什么? 我需要注册的jQuery(我认为WP虽然有jquery,但)? 我是否编辑分开队列调用?我需要添加一些东西到我的header.php?

+0

注意:我很抱歉花了我一个星期才把更多的东西放在这里,我不得不迁移它所在的服务器,同时寻找一份工作。 –

回答

3

你不需要添加jquery。如果没有添加,并且如果您的自定义脚本依赖于它(如您在代码中写的),它将通过wordpress添加。 这段代码就可以了(我只是测试它),但是..

取而代之的是:

if (!is_admin()) { 
    wp_enqueue_script('mdMenuAnimation'); 
} 

WordPress的recomed您使用钩子:

WordPress的食典:使用wp_enqueue_scripts行动调用这个函数,或者admin_enqueue_scripts在管理端调用它。

因此,它应该是这样的:

function my_scripts_method() { 
    wp_register_script('somehover', get_bloginfo('template_url').'/js-custom/hoverIntent.js', array('jquery')); 
    wp_enqueue_script('somehover'); 
} 

add_action('wp_enqueue_scripts', 'my_scripts_method'); 

WordPress的食典:使用wp_enqueue_scripts挂钩(而不是初始化钩许多文章的参考文献),我们避免注册替代的jQuery在管理页面上,这将导致后期编辑(除其他外)在经常升级后中断。

+0

好的,但即使当我使用该格式时,脚本也不会在前端加载,而且mdMenuAnimation.js中的操作也不会发生 –