Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to add jQuery to Underscores (_s) WordPress theme?

This might seem like a basic thing, but I'm unsure on how to add jQuery (using the CDN) into the Underscores WordPress starter theme. I did some searching but didn't really find anything, so I was hoping someone here could have an answer for me?

Thank you in advance!

like image 464
thosetinydreams Avatar asked Jul 28 '14 10:07

thosetinydreams


People also ask

Is not defined jQuery WordPress?

Although jQuery is a JavaScript library, it can often conflict with the other libraries JavaScript uses. This is the main reason for the appearance of the error in WordPress: “jQuery is not defined'. This means the system is unable to read your code, because the jQuery works as a middleman between the two parts.


2 Answers

The best method is to use the Wordpress function wp_enqueue_script() in your Underscores created theme functions.php file.

Find the function <THEME_NAME>_scripts (where <THEME_NAME> is your theme name when generated from Underscores website) and prepend the code below, under <THEME_NAME>_scripts function (before any other wp_enqueue_script)

// deregister default jQuery included with Wordpress
wp_deregister_script( 'jquery' );

$jquery_cdn = 'https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js';
wp_enqueue_script( 'jquery', $jquery_cdn, array(), '3.4.1', true );
like image 132
Rahil Wazir Avatar answered Nov 14 '22 04:11

Rahil Wazir


Underscores doesn't enque any javascript which rely on jquery. So a default install will not load the default jquery in WordPress without it being set as a dependency when enqueing a javascript file with wp_enqueue_script.

An example of loading bootstrap into underscore and loading jquery from WordPress is

wp_enqueue_script('bootstrap', get_template_directory_uri().'/assets/javascripts/bootstrap.min.js', array('jquery'),'v3',true);

You can do the same with a jquery file from a CDN registered in WordPress

like image 41
Anagio Avatar answered Nov 14 '22 03:11

Anagio