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.

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' );
Back to top ^

Join Paulund

  • Get access to 100s of premium tutorials and downloadable content
  • Members content consists of Premium WordPress plugins, CSS packages, jQuery packages, tutorial demo files and templates for 100s of web development tutorials
  • In-depth development tutorials
  • Priority tutorial requests
  • Priority email development support
  • No ads

Here at Paulund you'll find Web Development tutorials and snippets focusing mainly on PHP, WordPress and CSS. Members will get access to premium tutorials that go into more detail about development with these languages. You will also get access to downloadable premium content based on the tutorial.

Join Paulund

Leave a Reply

Your email address will not be published. Required fields are marked *