javascriptphpwordpresswordpress-themingwordpress-admin

wordpress how to add javascript to wp-admin


I am having a hard time on an easy task but seems like I can not find the answer.

I need to add some js code to the wp-admin page of a wordpress and woocommerce.

For this I have the following code on the functions.php:

function my_enqueue() {
    wp_enqueue_script('chcol01', plugin_dir_url(__FILE__) . '/aldisjs/admChangeColorScr.js');
}
    
add_action( 'admin_enqueue_scripts', 'my_enqueue' );

and I have this code on admChangeColorScr.js located on plugins/aldisjs:

function chcol(){
    alert("now what?");
}

What I expected is an alert notice on the wp-admin page when I relod but it does not happen.

What I am doing wrong??


Solution

  • First of all, you've defined the chcol function in your javascript file BUT YOU HAVE NEVER CALLED/USED IT!

    Second point in your code, when you try to inject your js file to admin (or any other page on wordpress), first check whether you're actually on that page or not. Although, admin_enqueue_scripts action hook should do the trick for you.

    For example, in your case, first check whether you're actually on the admin panel or not then inject/enqueue your js file! It never hurts to double check!!!

    function my_enqueue() {
      if(is_admin()){ // if it returns true 
        // Then run wp_enqueue_script() function!
      }
    }
    
    add_action( 'admin_enqueue_scripts', 'my_enqueue' );