Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How do I add a simple jQuery script to WordPress?

I have created a lot of websites on WordPress. For adding functionalities, I generally use WordPress plugins, but now I don’t want to add more number of plugins. I want to learn how to add a simple jQuery script to WordPress. How can I do it without using a plugin?

My function in WordPress functions.php is:

function add_my_script() {\n\n}

Which function can I used to add jQuery script to WordPress?


1 Answer
Amit D

WordPress is an open source CMS, used to develop dynamic websites. Let’s learn how to add jQuery script to WordPress. In the WordPress Theme folder, create a folder "js", and add a file in that. That file will be your Query file with extension “.js”. Add your jQuery script to that file. We have named it new.js,

Here’s your jQuery script:

jQuery(document).ready(function($) {
  $('#nav a').last().addClass('last');
});

Open your theme's functions.php file. Use the wp_enqueue_script() function so that you can add your script. 

Here’s the code:

add_action( 'wp_enqueue_scripts', 'add_my_script' );

function add_my_script() {
   // name your script to attach other scripts and de-register, etc.
   wp_enqueue_script (
    ‘new',
     get_template_directory_uri() . '/js/add_my_script.js',
   
     array('jquery') // this array lists the scripts upon which your script depends
   );
}

Assuming that your theme has wp_head and wp_footer in the right places, this will work. 

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.