How do I add a simple jQuery script to WordPress

How do I add a simple jQuery script to WordPress
? This is one of the questions many WordPress site owners are searching for answers. If you are one of them, I have shared a quick tutorial that I hope will answer any of the questions you might have about adding jQuery script to WordPress.

Here’s how I do it

Step 1: The first step is to make a new JavaScript file and put it in the desired theme folder. To do this, just go to your WordPress theme folder and create a subfolder and name it ‘js’. Add a file in the subfolder and then name it custom_scripts.js. Below is an example of the jQuery script that could go into this file.

    $('#nav a').1ast().addClass('1ast');

If you are familiar with jQuery, you may be asking why there is no $ sign at the beginning. In fact, the reason you are not seeing the dollar sign is because jQuery is variable name. jQuery is used instead of $ to avoid any conflicts with the WordPress theme.

Step 2: The next step is to add the custom_scripts.js into your theme’s functions.php file. If you are creating a theme from scratch or using a child theme, chances are there is no functions.php file in your theme. So you need to add it to your theme.

To add your custom_scripts.js file, just open your theme’s functions.php file. Then copy and paste the code below into the functions.php file. You can also add the file using the wp_enqueue_script() function.

The code to add is:

add_action( 'wp_enqueue_scripts', 'add_my_script');
function add_my_script(){
//name your script to attach other scripts and de-register, etc.
get_template_directory_uri() . '/js/add_my_script.js',
array('jquery') // this array lists the scripts upon which your script depend

If your theme has wp_footer and wp_head files, the jQuery script will be added in the header and footer sections. The only area where the script will not be loaded is in the admin pages.

Adding jQuery script to the WordPress Admin

Now it is time to add the jQuery script to the WordPress Admin. The process is quite simple and straightforward. All you need is to copy and add the code below into your theme’s functions.php file.

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' );

As you may have noticed, the code for adding jQuery script to the WordPress Admin is almost the same as the one used previously.

If you still need help on how to add a simple jQuery script to WordPress or any other WordPress related questions, just feel free to let me know. I will be happy to help you.

Leave a Reply

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