Organizational Research By

Surprising Reserch Topic

adding jquery and custom scripts to a wordpress theme

adding jquery and custom scripts to a wordpress theme  using -'jquery,wordpress,wordpress-theming'

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_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://", false, null);
   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?

asked Oct 23, 2015 by badhwar.rohit
0 votes

Related Hot Questions

1 Answer

0 votes

First, wp_enqueue_scripts only runs on the frontend, so you don't need the is_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:

add_action( "wp_enqueue_scripts", "my_js_so_14864221", 11 );

function my_js_so_14864221() 
        get_stylesheet_directory_uri() . '/js/theme.js', 
        array( 'jquery' ), 

And your jQuery code in theme.js should be encapsulated like:

jQuery(document).ready(function($) {   
    // $('#your-stuff').animate().hide().whatever();
answered Oct 23, 2015 by 20shahi