1

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 4

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

@AnandChoudhary If this answer would be helpful to you then please mark it as approved so it could be helpful for others.
0

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']);

Comments

0

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');
}

Comments

-1

Just do something like this:

wp_enqueue_script('custom-js', get_template_directory_uri() . '/custom.js', array('jquery'), null, true);

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.