JQuery in wordpress

Setup One


https://stackoverflow.com/questions/11159860/how-do-i-add-a-simple-jquery-script-to-wordpress

First you need to write your script. In your theme folder create a folder called something like ‘js’. Create a file in that folder for your javascript. E.g. your-script.js.

Add your jQuery script to that file (you don’t need < script > tags in a .js file).

Here is an example of how your jQuery script (in wp-content/themes/your-theme/js/your-scrript.js) might look:

[code]
jQuery(document).ready(function($) {
$(‘#nav a’).last().addClass(‘last’);
})
[/code]

Notice that I use jQuery and not $ at the start of the function.

Ok, now open your theme’s functions.php file. You’ll want to use the wp_enqueue_script() function so that you can add your script whilst also telling WordPress that it relies on jQuery. Here’s how to do that:

[code language=”php”]
add_action( ‘wp_enqueue_scripts’, ‘add_my_script’ );
function add_my_script() {
wp_enqueue_script(
‘your-script’, // name your script so that you can attach other scripts and de-register, etc.
get_template_directory_uri() . ‘/js/your-script.js’, // this is the location of your script file
array(‘jquery’) // this array lists the scripts upon which your script depends
);
}
[/code]

Assuming that your theme has wp_head and wp_footer in the right places, this should work. Let me know if you need any more help.

WordPress questions can be asked over at WordPress Answers – https://wordpress.stackexchange.com/.


https://premium.wpmudev.org/blog/adding-jquery-scripts-wordpress/


How To Properly Add jQuery Scripts To WordPress



WordPress has been in our lives for over 16 years, yet the method of adding scripts to themes and plugins still remains a mystery for many developers. In this article we finally put the confusion to rest.

Since it’s one of the most commonly used Javascript libraries, today we’re discussing how to add simple jQuery scripts to your WordPress themes or plugins.

But first…

About jQuery’s Compatibility Mode

Before we start attaching scripts to WordPress, it’s important to understand jQuery’s compatibility mode.

As you’re probably aware, WordPress comes pre-loaded with jQuery, which you can use with your code.

WordPress’ jQuery also has a “compatibility mode,” which is a mechanism for avoiding conflicts with other language libraries.

Part of this defense mechanism means you cannot use the $ sign directly as you might in other projects.

Instead, when writing jQuery for WordPress you need to use jQuery.

Check out the code below for an example:

/* Regular jQuery */
$(‘.hideable’).on(‘click’, function() {
$(this).hide();
})
/* Compatibility Mode */
jQuery(‘.hideable’).on(‘click’, function() {
jQuery(this).hide();
})

view raw
compatibility.js
hosted with ❤ by GitHub

The problem is, writing jQuery a gazillion times takes longer, makes it harder to read, and can bloat your script.

The good news?

With a few modifications you can go back to using our lovely little dollar sign once again.

BTW, if you’re new to jQuery, the $ sign is just an alias to jQuery(), then an alias to a function.

The basic structure looks like this: $(selector).action(). The dollar sign defines jQuery… the “(selector)” queries or finds HTML elements… and finally the “jQuery action()” is the action to be performed on the elements.

Back to how we can get around our compatibility issue… here are a couple of viable options:

1.Enter jQuery Stealth Mode

The first way to get around compatibility mode is to get stealthy with your code.

For example, if you’re loading your script in the footer, you can wrap your code in an anonymous function, which will map jQuery to $.

Like in the example below:

If you want to add your script in the header (which you should avoid if possible, more on that below) you can wrap everything in a document-ready function, passing $ along the way.

jQuery(document).ready(function( $ ) {
$(‘.hideable’).on(‘click’, function() {
$(this).hide();
})
});

2.Enter “No Conflict” Mode

Another simple way to avoid spelling out jQuery is to enter “no conflict” mode and use a different shortcut.

In this case: $j instead of the default $.

All you have to do is declare this at the top of your script:var $j = jQuery.noConflict();

Alright, now you know more about writing valid jQuery code for WordPress, let’s add it to our website.

How To Add jQuery Scripts To WordPress

One of the simplest ways to add jQuery scripts to WordPress is via a process called “enqueueing.”

For a regular HTML website, we would use the <link> element to add scripts. WordPress ends up doing the same thing, but we’ll use special WP functions to achieve it.

This way, it handles all our dependencies for us (thanks WP!).

If you’re working on a theme, you can use the wp_enqueue_script() function within your functions.php file.

Here’s what it looks like:

function my_theme_scripts() {
wp_enqueue_script( ‘my-great-script’, get_template_directory_uri() . ‘/js/my-great-script.js’, array( ‘jquery’ ), ‘1.0.0’, true );
}
add_action( ‘wp_enqueue_scripts’, ‘my_theme_scripts’ );

view raw
enqueue-theme.php
hosted with ❤ by GitHub

This function takes five arguments:

  1. $handle – a unique handle you can use to refer to the script.
  2. $src – the location of the script file.
  3. $deps – specifies an array of dependencies.
  4. $ver – the version number of your script.
  5. $in_footer – lets WordPress know where to put the script.

*Something to note about $in_footer is that by default, scripts will be loaded in the header.

This is bad practice and can drastically slow down your site. Therefore, if you want to place your script in the footer, make sure this parameter is set to true.

Adding Scripts To The WordPress Admin

You can also add scripts to the admin. The functions used are exactly the same, you just need to use a different hook.

For example:

function my_admin_scripts() {
wp_enqueue_script( ‘my-great-script’, plugin_dir_url( __FILE__ ) . ‘/js/my-great-script.js’, array( ‘jquery’ ), ‘1.0.0’, true );
}
add_action( ‘admin_enqueue_scripts’, ‘my_admin_scripts’ );

view raw
enqueue-backend.php
hosted with ❤ by GitHub

Instead of hooking into wp_enqueue_scripts we need to use admin_enqueue_scripts.

That’s it!

Really.

How To De-Register WordPress’ jQuery

But what if you want to use a version of jQuery different to the one WordPress pre-loads?

You could enqueue it… but that leaves two versions of JQ on the page.

To avoid this we have to de-register WP’s version.

Here’s what this looks like:

// include custom jQuery
function shapeSpace_include_custom_jquery() {
wp_deregister_script(‘jquery’);
wp_enqueue_script(‘jquery’, ‘https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js’, array(), null, true);
}
add_action(‘wp_enqueue_scripts’, ‘shapeSpace_include_custom_jquery’);

view raw
gistfile1.txt
hosted with ❤ by GitHub

It’s as simple as using the wp_deregister_script() to de-register WP’s jQuery, and then including the jQuery script you want to add.

In the example above we used Google-hosted jQuery library, but you’ll obviously replace it with the URL of your own script.

Shouldn’t You Register Scripts Before Enqueuing?

If you want to load your scripts when needed instead of directly loading them in your pages – you can register the script earlier on.

For example, on wp_loaded:

add_action( ‘wp_loaded’, ‘register_all_scripts’ );
function register_all_scripts()
{
wp_register_script(…);
}

view raw
gistfile1.txt
hosted with ❤ by GitHub

Once you’ve done this you can then enqueue the scripts when you need them:

add_action( ‘wp_enqueue_scripts’, ‘enqueue_front_scripts’ );
add_action( ‘admin_enqueue_scripts’, ‘enqueue_back_scripts’ );

view raw
gistfile1.txt
hosted with ❤ by GitHub

Just remember to use the same names to avoid colliding with other scripts.

Using Conditional Tags

Use conditional tags to only load your scripts when necessary.

This is used more often in admin, where you’d want to use a script on a specific page only (not the whole admin). This also saves bandwidth and processing time – which means faster loading times for your website.

Take a look at the admin enqueue scripts documentation in the WordPress Codex for more information.

Add jQuery To WordPress Using Plugins

The WP plugin directory also has plenty of great plugins you can use to insert scripts to your WordPress posts, pages, or themes.

Some well known JavaScript / jQuery plugin examples include: Advanced Custom Fields, Simple Custom CSS and JS, Scripts n Styles, and Asset CleanUp.

Script Your Own jQuery Story

Gaining a better understanding of jQuery is only going to make the work you do more impactful. Whether it’s for your own website, or client projects.

jQuery is well known for its simplicity, and as you’ve (hopefully) learned in this article, adding simple jQuery scripts to WordPress is easy as pie once you know how.

Yes, there is a little bit of an overhead compared to using vanilla HTML, but there’s also the added benefit of dependency management and clarity.

Not only this, by employing little tricks like bypassing jQuery’s WP default compatibility, you’re going to save yourself a lot of time, effort, and bloated code.

Scroll to Top