注册要在admin和前端同时入队的脚本


12

据我了解,管理脚本应该通过admin_enqueue_scripts钩子和所有其他脚本进行注册和入队,wp_enqueue_scripts因此我设置了以下功能,以一种清晰且有组织的方式注册和入队所有脚本。

我的问题是,如果我在admin和前端都需要某些脚本(例如jquery validate插件)怎么办?在这种情况下,建议使用什么方法来注册和排队脚本?用不同的$ handle注册两次或wp_enqueue_scripts仅通过$ handle注册,如果是这样,是否不存在在需要时不被调用的风险?(我的意思是,admin_enqueue_scripts如果不更早提供这些脚本,为什么还会存在其他原因?

我真的很感谢有人向我解释这一点,以充分理解wp中排队脚本的细微差别。谢谢

我的代码:

// REGISTER ALL NON-ADMIN SCRIPTS
add_action( 'wp_enqueue_scripts', 'register_all_non_admin_scripts' );
function register_all_non_admin_scripts() {

wp_register_script( ... );
wp_register_script( ... );

}

// ENQUEUE NON-ADMIN SCRIPTS CONDITIONALLY
add_action( 'wp_enqueue_scripts', 'enqueue_scripts_where_required' );
function enqueue_scripts_where_required() {

// scripts to be loaded at all times
wp_enqueue_script( '' );

// scripts to be loaded conditionaly
if( is_page( '' ) ) {
    wp_enqueue_style( '' );
}
}

// REGISTER ALL ADMIN SCRIPTS
add_action( 'admin_enqueue_scripts', 'register_all_admin_scripts' );
function register_all_admin_scripts(){
wp_register_script( ... );
wp_register_script( ... );
}

// ENQUEUE ADMIN SCRIPTS
add_action( 'admin_enqueue_scripts', 'enqueue_admin_contact_cpt_js' );
function enqueue_admin_contact_cpt_js(){

global $post_type;

// scripts to be loaded at all times
wp_enqueue_script( '' );

// scripts to be loaded conditionaly by post type
if( 'contact' == $post_type ){
    wp_enqueue_script( '' );
    ...
}
}

Answers:


10

您可以更早注册脚本,例如wp_loaded

add_action( 'wp_loaded', 'register_all_scripts' );

function register_all_scripts() 
{
    wp_register_script(...);
}

然后,在需要脚本时将它们排入队列

add_action( 'wp_enqueue_scripts', 'enqueue_front_scripts' );
add_action( 'admin_enqueue_scripts', 'enqueue_back_scripts' );

使用相同的句柄和名称,以避免与其他脚本冲突。


我想这将解决用于admin和前端的脚本的问题。在这些情况下,我将添加另一个功能。感谢@toscho
Ronnieinspain 2013年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.