Doing some searching through Google, I came across the same bit of code over and over for adding jQuery to a from-scratch WordPress theme.
if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11);
function my_jquery_enqueue() {
wp_deregister_script('jquery');
wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);
wp_enqueue_script('jquery');
wp_enqueue_script('my_script', get_bloginfo('template_url') . '/js/theme.js', array('jquery'), '1.0', true);
}
I’ve added this code to my functions.php file, and I created a js folder and made a theme.js file using the following syntax in it:
jQuery(function ($) {
/* You can safely use $ in this code block to reference jQuery */
});
When I refresh my WP site, the theme.js file doesn’t seem to be called. In Chrome Dev tools, it’s not listed among the js files being rendered.
Am I using an outdated approach? How can I make my /js/theme.js file, using jquery, work for my theme?
First,
wp_enqueue_scripts
only runs on the frontend, so you don’t need theis_admin()
check.Second, only de-register the default jQuery (bundled with WP) if you really know what you are doing. In your example, you are loading an outdated version from Google (current is 1.8.3, not 1.7.1). Also, see: Donât Dequeue WordPressâ jQuery
Third, you should be using
get_stylesheet_directory_uri
, which is the correct function that will count for parent and child theme folders.Finally, this code works ok in
/themes/my-theme/functions.php
:And your jQuery code in theme.js should be encapsulated like: