1

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??

1
  • Where are u calling the chcol function, I think it does not shows alert because the chcol function is never called. Also, check from network files if the js file is getting loaded in wp-admin page Commented Mar 27, 2021 at 13:41

1 Answer 1

3

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' );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.