How to correctly add Javascript in functions.php

I would like to remove some ugly looking arrows that are standard on cart buttons in WooCommerce. To achieve this, I found a tip of adding the following code, which should remove the arrows when the document has loaded.

I assume I am going to put it in my functions.php? How exactly would I do that?

$(document).ready(function() {
    $(".woocommerce-cart").html(function(i, val) {
    return val.replace(" →", "");
    });
    $(".woocommerce-cart").html(function(i, val) {
    return val.replace("← ", "");
    });
});

EDIT

Okay. I’ve tried this approach:

Made a file named ‘removeArrows.js’ and placed it in my plugin folder. This has the same content as the original code, except jQuery instead $. Then I added the following to functions.php:

function wpb_adding_scripts() {
      wp_register_script('my_amazing_script', plugins_url('removeArrows.js', FILE), array('jquery'),'1.1', true);
     wp_enqueue_script('my_amazing_script');
 } 

add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' ); 

I can’t figure out how to make the code display properly. This did not work. Any suggestions to make this work?

jQuery Snippet Source

4

Your $scr in your wp_register_script() function is wrong. Given that your functions.php is inside your plugin, and your removeArrows.js is in the root of your plugin, your $scr should look like this

plugins_url( '/removeArrows.js' , __FILE__ )

Another point of note, it is always good practice to load your scripts and styles last. This will ensure that it will not get overriden by other scripts and styles. To do this, just add a very low priority (very high number) to your priority parameter ($priority) of add_action.

 add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts', 999 ); 

And always load/enqueue scripts and styles via the wp_enqueue_scripts action hook, as this is the proper hook to use. Do not load scripts and styles directly to wp_head or wp_footer

EDIT

For themes, as you’ve indicated that you now moved everything to your theme, your $scr would change to this

 get_template_directory_uri() . '/removeArrows.js'

for parent themes and this

get_stylesheet_directory_uri() . '/removeArrows.js'

for child themes. Your complete code should look like this

function wpb_adding_scripts() {
    wp_register_script('my_amazing_script', get_template_directory_uri() . '/removeArrows.js', array('jquery'),'1.1', true);
    wp_enqueue_script('my_amazing_script');
} 

add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts', 999 ); 

Leave a Comment