How to add your custom css or js on admin screen?
How to add your custom CSS or JS on admin screen? Well, it’s pretty easy. We need to hook into admin_enqueue_scripts
action and this is the best and only solution. So, let’s write some code:
1 2 3 4 5 6 7 8 |
if ( is_admin() ) { add_action( 'admin_enqueue_scripts', 'my_admin_enqueue_scripts' ); } function my_admin_enqueue_scripts( $hook ) { wp_enqueue_style( 'my-stylesheet', plugins_url( 'css/admin.css', __FILE__ ) ); wp_enqueue_script( 'my-script', plugins_url( 'js/admin.js', __FILE__ ) ); } |
Please note the $hook
variable. Thanks to its value you may enqueue your scripts/styles depending on active admin screen. It is important, because you should not enqueue your scripts or styles where it isn’t necessary.
Second thing, first conditional
is_admin
. It’s pretty obvious, but I have to mention it. Do not even hook into admin_enqueue when you are not on admin screen.
One Comment
coloradocolin
This is a great explanation. I have dabbled in this, but didn’t always know what I was doing! This helped me to understand some of the basics.