There are several methods to integrate jQuery into WordPress effectively.
WordPress runs jQuery in a compatibility mode to prevent conflicts with other scripts or libraries. In this mode, jQuery is used without the ‘$‘ sign, which leads to code like this:
jQuery('.classname').on('click', function() {
jQuery(this).show();
});
However, writing out ‘jQuery‘ every time instead of using the ‘$‘ sign can be cumbersome and time-consuming. You can simplify this by declaring the ‘$‘ sign within a function at the beginning of your code, allowing you to use ‘$‘ as usual:
jQuery(document).ready(function( $ ) {
$('.classname').on('click', function() {
$(this).show();
});
});
After writing your jQuery code, save it as a ‘.js‘ file, such as ‘filename.js‘. In this example, we’ll assume the file is stored in the ‘js‘ directory within your theme folder.
Once your JS file is created, the next step is to register and enqueue it within your theme using PHP in the ‘functions.php‘ file.
If you’re working with your primary theme, the code will look like this:
function your_theme_scripts() {
wp_enqueue_script( 'custom-script', get_template_directory_uri() . '/js/filename.js', array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'your_theme_scripts' );
For a child theme, the code is slightly different:
function your_theme_scripts() {
wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/filename.js', array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'your_theme_scripts' );
By following these steps, you can seamlessly add jQuery to your WordPress site while keeping your code clean and efficient.