how to load js using wp_enqueue_script?

+1 vote
asked Sep 12, 2017 by anand-choudhary

I'm trying to call js library using wp_enqueue_script. but I can't figure out what I'm mistaking here also, I want to use for plugins Please tell me how to use my plugins directory.

add_action('wp_enqueue_scripts', 'add_custom_script');
function add_custom_script(){
  wp_enqueue_script( 
    'jquery-custom-script',
    get_template_directory_uri().'/js/jquery-custom-script.js'
 );
}

can anyone figure out what I'm mistaking here .

4 Answers

+2 votes
answered Sep 12, 2017 by purvik7373

You can use plugin_dir_url function.

Example:

/**
 * Include CSS file for MyPlugin.
 */
function myplugin_scripts() {
    wp_register_script( 'foo-js',  plugin_dir_url( __FILE__ ) . 'assets/foo-custom.js' );
    wp_enqueue_script( 'foo-js' );
}
add_action( 'wp_enqueue_scripts', 'myplugin_scripts' );

If you pass __FILE__ as argument of the get the current PHP script file path

0 votes
answered Sep 12, 2017 by klumme

If you want to load the JS from a plugin, let's say inside the plugins/my-plugin directory, and the code runs in a file directly inside plugins/my-plugin, do something like this (also added a parameter explicitly specifying jQuery as a dependency of your script):

wp_enqueue_script('jquery-custom-script', plugin_dir_url(__FILE__) . 'js/jquery-custom-script.js', ['jquery']);
–1 vote
answered Sep 12, 2017 by luka-a

Just do something like this:

wp_enqueue_script('custom-js', get_template_directory_uri() . '/custom.js', array('jquery'), null, true);
0 votes
answered Sep 12, 2017 by j-kar

the best way to insert js and css in a wordpress plugin is

first register your files and second use them.

 // register scripts and style on initialization
add_action('init', 'register_style');
function register_style() {
    wp_register_style( 'style', plugins_url('/css/style.css', __FILE__), false, '1.0.0', 'all');
    wp_register_script( 'scripts', plugins_url('/js/scripts.js', __FILE__));
}

// use the registered scripts and style above
add_action('wp_enqueue_scripts', 'enqueue_style');

function enqueue_style(){
   wp_enqueue_style( 'style' );
   wp_enqueue_script('scripts');
}
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...