0

I am learning WordPress plugin development. Now I need to place jQuery code in one file. Where can I place jQuery code ?

  • 2
    Have you double-checked to make sure jQuery isn't already running wherever you need it? Most themes include it on the front end, and it's typically also included on the back end. Where are you trying to include it? – WebElaine Feb 4 at 16:26
  • Thanks @WebElaine. I would like to export a JavaScript file with my plugin as ZIP format. Where can I place the javascript file ? Thanks. – Foysal Feb 4 at 16:42
  • 1
    @WebElaine I don't believe the OP knows how to create a javascript file and load it in the browser via a plugin – Tom J Nowell Feb 4 at 16:51
2

You should place the .js file into your plugin directory (it can be root or any other folder like assets or js).

To enqueue JS and CSS files in the front-end:

function wp_357866_enqueue_frontend()
{
    wp_enqueue_script('your-script', get_template_directory_uri() . '/path/to/js/your-script.js', array(), null, true); // You should set the last parameter to 'true' to load JS in the footer
    wp_enqueue_style('your-style', get_stylesheet_directory_uri() . '/path/to/css/your-style.css', array(), null);
}
add_action( 'wp_enqueue_scripts', 'wp_357866_enqueue_frontend' );

Reference: wp_enqueue_scripts

To enqueue JS and CSS in the administration:

function wp_357866_enqueue_admin()
{
    wp_enqueue_script('your-script', get_template_directory_uri() . '/path/to/js/your-script.js', array(), null, true); // You should set the last parameter to 'true' to load JS in the footer
    wp_enqueue_style('your-style', get_stylesheet_directory_uri() . '/path/to/css/your-style.css', array(), null);
}
add_action( 'admin_enqueue_scripts', 'wp_357866_enqueue_admin' );

Reference: admin_enqueue_scripts

  • Thanks @Cadu De Castro Alves, How to use admin_enqueue_scripts hook ? Some sample code is helpful. – abu abu Feb 8 at 15:05
3

You should place your javascript inside a .js file in your plugin, then enqueue it using the wp_enqueue_script function on the appropriate hook. Be sure to declare jquery as a dependency when you call wp_enqueue_script, and be sure to call it on the correct hook or WordPress will complain

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.