Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I add a simple jQuery script to WordPress?
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 jQuery file with extension ".js". Add your jQuery script to that file. We have named it new.js.
Step 1: Create Your jQuery Script File
Here's your jQuery script ?
jQuery(document).ready(function($) {
$('#nav a').last().addClass('last');
});
Step 2: Enqueue the Script in functions.php
Open your theme's functions.php file. Use the wp_enqueue_script() function to properly add your script to WordPress. This is the recommended way to include JavaScript files in WordPress as it handles dependencies and prevents conflicts.
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/new.js',
array('jquery') // this array lists the scripts upon which your script depends
);
}
Important Notes
Assuming that your theme has wp_head and wp_footer in the right places, this will work. The wp_enqueue_script() function ensures that jQuery is loaded before your custom script, and it prevents the same script from being loaded multiple times.
Make sure the file path in your PHP code matches the actual location of your JavaScript file. In this example, we're using new.js inside the js folder of your active theme.
Conclusion
By following these steps, you can safely add jQuery scripts to WordPress using the proper enqueueing method, ensuring compatibility and preventing conflicts with other plugins or themes.
