How to load jQuery only for a specific page in a WordPress theme

To load jQuery only for a specific page in a WordPress theme, you can use conditional tags to check for the page ID, slug, or title, and then enqueue the script only for that page. Follow these steps:

  1. In your WordPress admin dashboard, go to “Appearance” > “Theme Editor.”
  2. In the right sidebar, locate and click on the “functions.php” file.
  3. Add the following code snippet at the end of the file:
function my_theme_enqueue_scripts() {
    // Replace 'your-page-slug' with the slug of the specific page
    if (is_page('your-page-slug')) {
        // Register your custom script with jQuery as a dependency
        wp_register_script('my-custom-script', get_template_directory_uri() . '/js/my-custom-script.js', array('jquery'), '1.0', true);

        // Enqueue your custom script
        wp_enqueue_script('my-custom-script');
    }
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_scripts');

Replace ‘your-page-slug’ with the slug of the specific page where you want to load jQuery. Replace /js/my-custom-script.js with the path to your custom JavaScript file.

This code snippet creates a function called my_theme_enqueue_scripts() that checks if the current page matches the specified slug, and if so, registers and enqueues your custom script with jQuery as a dependency.

  1. Click “Update File” to save the changes.

Now, jQuery and your custom script will be loaded only on the specified page.

When using jQuery in your custom script, make sure to use the jQuery object instead of the $ alias, as WordPress runs jQuery in no-conflict mode. You can wrap your code in an immediately-invoked function expression (IIFE) like this:

(function($) {
    // Your custom jQuery code here, using the $ alias
    $(document).ready(function() {
        // Your code that needs to run when the DOM is ready
    });
})(jQuery);

Remember to always backup your files before making any changes, and test your changes on a staging site or local development environment before applying them to your live site.

Leave a Reply

Your email address will not be published. Required fields are marked *