When building WordPress themes, I typically try to keep as much code as possible out of the head
section of my template and instead rely on the wp_head()
action hook. By putting all of my wp_register_script()
and wp_register_style()
calls in one function I have a single place to manage (theme) assets and their dependencies. At the bottom of the function I usually like to enqueue my global scripts and styles (ones that will always be present) but am careful to keep them from appearing in the WordPress administration area (if you’re dealing with custom admin scripts or styles obviously adjust this to fit your project):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function grunwell_enqueue_scripts_styles() { wp_register_style( 'my-style', get_bloginfo( 'template_url' ) . '/css/base.css' ); wp_register_script( 'my-script', get_bloginfo( 'template_url' ) . '/js/main.js' ); // Don't enqueue these for pages in the admin area if ( ! is_admin() && ! is_login_page() ) { wp_enqueue_style( 'my-style' ); wp_enqueue_script( 'my-script' ); } } add_action( 'init', 'grunwell_enqueue_scripts_styles' ); |
Wait, what the heck is is_login_page()
Did you catch that? My approach uses a non-core function, is_login_page()
, which detects if the current page is a login-style page. The code is adapted from TheDeadMedic’s answer to to a question on WordPress Answers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/** * Check to see if the current page is the login/register page. * * Use this in conjunction with is_admin() to separate the front-end * from the back-end of your theme. * * @return bool */ if ( ! function_exists( 'is_login_page' ) ) { function is_login_page() { return in_array( $GLOBALS['pagenow'], array( 'wp-login.php', 'wp-register.php' ), true ); } } |
Since is_admin()
doesn’t include the login-type pages (wp-login.php
and wp-register.php
) – any form scripting or styles could potentially impact the login page. Using is_login_page()
with the is_admin()
conditional will let you keep your scripts and styles out of the core WordPress pages.
artur99
Thx!
Peter
Very helpful thanks!