How To Check If In WordPress Admin Area

Wordpress Dashboard
When creating WordPress plugins and themes, I find that a lot of the time you need to do something in the admin area only.

For example you might want to add admin only CSS or admin only Javascript. You might only want to add this so you can give extra functionality to your plugin in dashboard screen.

Normally in your WordPress plugin you would just call wp enqueue script in the constructor of your plugin. But the problem with this is that if you add something here the script will be added to the page even on the front-end. Adding Javascript to the page is adding more weight to page even when the functionality can't be used.

To fix this sort of problem you can use the WordPress action admin_enqueue_script which will allow you to only load stylesheets in the admin area.

<?php 
add_action( 'admin_enqueue_scripts', 'function_name' ); 
?>

Now you can create the callback function to use when you this action is called.

function load_wp_admin_style() {
        wp_register_style( 'wp_admin_css', get_bloginfo( 'stylesheet_directory' ) . '/admin-style.css', false, '1.0.0' );
        wp_enqueue_style( 'wp_admin_css' );
}
add_action( 'admin_enqueue_scripts', 'load_wp_admin_style' );

This will add a stylesheet to every admin page you go on, but if you are building a WordPress plugin then you don't want to load the stylesheet on every page you want to just load it on a specific page.

To load it on a specific page you need to check the page before you enqueue the stylesheets.

function load_wp_admin_style( $hook ) {
        if( $hook == 'edit.php')
        {
              wp_register_style( 'wp_admin_css', get_bloginfo( 'stylesheet_directory' ) . '/admin-style.css', false, '1.0.0' );
              wp_enqueue_style( 'wp_admin_css' );
        }
}
add_action( 'admin_enqueue_scripts', 'load_wp_admin_style' );

Advertise here 50% Off

Comment