2012-05-26 42 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中的操作也不會發生 –