WordPress already includes jQuery by default. However, it follows a slightly different approach to ensure compatibility with other JavaScript libraries. Here’s how you can use jQuery in WordPress:
1. Enqueue jQuery Properly
First, make sure you’re enqueuing jQuery in your theme or plugin. WordPress includes its own version of jQuery, so you should load it using WordPress’s wp_enqueue_script
function.
In your functions.php
file, add this code to ensure jQuery is properly enqueued:
function enqueue_jquery() {
// Ensure jQuery is loaded
wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'enqueue_jquery');
2. Use jQuery in Your Script
Once jQuery is loaded, you can write your jQuery code. WordPress runs in no-conflict mode, meaning $
is not available directly to avoid conflicts with other libraries. Instead, you should use jQuery
.
Example:
jQuery(document).ready(function($) {
// Your jQuery code here
$('.my-element').click(function() {
alert('Element clicked!');
});
});
Notice that jQuery(document).ready()
is used instead of $(document).ready()
, and $
is passed as a parameter to the function to enable the use of $
within the code block.
3. Include Custom jQuery in Your Theme
If you need to add custom JavaScript (including jQuery) in your WordPress theme, you can enqueue your custom script as well:
function enqueue_custom_script() {
wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom-script.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_custom_script');
In this example:
'custom-script'
is the handle for your script.- The third parameter
array('jquery')
ensures that jQuery is loaded as a dependency before your script runs. - The
null
in the version parameter can be replaced with a specific version if needed. - The
true
argument loads the script in the footer, which is recommended for performance reasons.
Now you can add your jQuery code in the custom-script.js
file.
4. Using jQuery Directly in Theme Files
If you want to add jQuery directly in a template file (like header.php
or footer.php
), you can add it within <script>
tags like this:
<script>
jQuery(document).ready(function($) {
$('.my-element').click(function() {
alert('Element clicked!');
});
});
</script>