As i understand it, admin scripts are supposed to be registered and enqueued through the admin_enqueue_scripts
hook and all other scripts at wp_enqueue_scripts
so i have set up the following functions to register and enqueue all my scripts in a clear and organized way.
My question is, what if i need certain scripts (eg. jquery validate plugin) both in admin and on the front end? what is the recommended method for registering and enqueuing the script in this case? register it twice with diferent a $handle or register it through wp_enqueue_scripts
only and if so, is there not the risk of it not being called when required ? (i mean, why else would admin_enqueue_scripts
exist if not to make those scripts available at an earlier time?
I would really appreciate someone explain this to me to fully understand the nuances of enqueuing scripts in wp. Thanks
My code:
// 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( '' );
...
}
}
You can register the scripts earlier, for example on
wp_loaded
:And then you enqueue the scripts whenever you need them:
Use the same handles and names to avoid collisions with other scripts.
You can also use one hook to include common assets, instead of calling hook for admin and frontend separately like