Need help de-registering and enqueing specifc JS files in a WordPress child theme

I'm currently working on customizing a WordPress site that has child theme activated, and I have these 2 different JavaScripts that are being injected into the footer:

<script type='text/javascript' src='https://royalpalm.com/wp-content/themes/houzez/js/houzez_ajax_calls.js?ver=1.5.7.3'></script>
<script type='text/javascript' src='https://royalpalm.com/wp-content/themes/houzez/js/custom.js?ver=1.5.7.3'></script>

Open in new window


To clarify .. these 2 lines of JavaScript are NOT hardcoded into the child theme's footer.php file .. they're being injected into the footer programatically via the wp_footer() method.

How would I go about properly de-registering these 2 JavaScripts, .. and enqueuing my own JS files that I've copied over to my child theme -- WITHOUT applying any changes directly to the parent theme files?  

More specifically .. I'd like to replace the 2 lines of JavaScript (above) with these 2 lines below (ie: note the different "houzez-child" theme folder name):

<script type='text/javascript' src='https://royalpalm.com/wp-content/themes/houzez-child/js/houzez_ajax_calls.js?ver=1.5.7.3'></script>
<script type='text/javascript' src='https://royalpalm.com/wp-content/themes/houzez-child/js/custom.js?ver=1.5.7.3'></script>

Open in new window


It's my understanding is that this can be accomplished by adding some code to my child theme's functions.php file, .. but so far I haven't been able to figure out the proper way to do it.  Please advise.

Thanks,
- Yvan
egoselfaxisAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
Normally you would use the wp_dequeue_script() and possibly wp_deregister_script() methods in your functions.php file. Both of those methods take in the 'handle' of a script, which would be set when it's registered - likely in the parent's functions.php file (or included file). You would need to look through your parent's function calls to see how they were enqueued and what handle was given to them. For example, you might see something like this:

function add_scripts() {
    wp_enqueue_script( 'script_handle_1', get_stylesheet_directory_uri() . '/someScript.js');
} 
add_action( 'wp_enqueue_scripts', 'add_scripts' );

Open in new window

You would then hook an action in your child theme:

function remove_scripts() {
    wp_dequeue_script( 'script_handle_1' );
}
add_action( 'wp_print_scripts', 'remove_scripts' );

Open in new window

You would then need to enqueue your new scripts in your child theme
Scott Fell, EE MVEDeveloper & EE ModeratorCommented:
If you need to do this for a specific page, this is what I came up with for something I am currently working on where I want my ajax script to show up only on one page.  Notice my filter is  $wp_query->post->post_title; and that is because my two choices where the page id or the post title.  

add_action( 'wp_enqueue_scripts', 'ajax_signup_enqueue_scripts' );
function ajax_signup_enqueue_scripts() {


    if(is_page()){ //Check if we are viewing sign up page
        global $wp_query;


        //get page name
        $pagename = $wp_query->post->post_title;

       if($pagename == 'Title Of Page'){

           
            wp_enqueue_script(
                'uniquename',
                plugins_url( '/path_to_js_file.js', __FILE__ ),
                array('jquery'),
                '1.0', true
            );

            wp_localize_script(
                'uniquename',
                'uniquename',
                array(
                    'ajaxurl' => admin_url( 'admin-ajax.php'
                    )
                )
            );

       }
        
   }

}

Open in new window


If you do a variable dump or print_r of $wp_query you can see what is available on that page
global $wp_query; 
print_r($wp_query): 

Open in new window

egoselfaxisAuthor Commented:
Thanks for this Scott, .. but I actually need for this to be globally replaced within my child theme (it's not just for one specific post). Thanks for your input though.

- Yvan
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Chris StanyonWebDevCommented:
Have you tried what I suggested - that's for replacing it across your entire site
egoselfaxisAuthor Commented:
Chris -- yes, I've been trying to implement what you suggested, but it doesn't appear to be working.

I located this line in my register-scripts.php file that's contained within my parent theme folder:

wp_enqueue_script('houzez-custom', get_template_directory_uri() . '/js/custom' . $js_minify_prefix . '.js', array('jquery'), HOUZEZ_THEME_VERSION, true);

Open in new window


So I then tried adding the following to the functions.php file that's contained within my child theme folder:

function remove_scripts() {
    wp_dequeue_script( 'houzez-custom' );
}
add_action( 'houzez-custom', 'remove_scripts' );

Open in new window


Yet when I reload the site and view the underlying source code, I still don't see any difference.

I suspect that it's because the "houzez-custom" method is being bundled with other scripts and loaded in a single instance on this 1 line:

add_action( 'wp_enqueue_scripts', 'houzez_scripts' );

Open in new window


There's a "houzez_scripts()" method in the register-scripts.php file that's about 600 lines.  I'm really hoping that I won't have to copy the entire thing over to my functions.php file. Any thoughts / suggestions?

- Yvan
Chris StanyonWebDevCommented:
OK. That first line of code is enqueueing your script with a handle of houzez-custom.

In your child theme functions file you need to dequeue it using the same handle. Your remove_scripts() function is correct, but not the way you're calling it. The add_action() method takes in a 'hook' and a function name. The 'hook' basically tells wordpress when to fire a certain function. You've passed in the name of your script as the hook, rather than the Wordpress hook name. Look at my original code:

add_action( 'wp_print_scripts', 'remove_scripts' );

This says to fire the remove_scripts function when WordPress calls the wp_print_scripts hook. Effectively, just before Wordpress is about to output the scripts to your page it will call that hook and your function will fire - dequeueing the script so it doesn't get output.
egoselfaxisAuthor Commented:
My apologies, but I'm a bit confused.  It appears that I'm doing it just as you've described.   In my case, the logic is ...

"Fire the remove_scripts function when WordPress calls the houzez-custom hook"

function remove_scripts() {
    wp_dequeue_script( 'houzez-custom' );
}
add_action( 'houzez-custom', 'remove_scripts' );

Open in new window


Could you please clarify what you mean?  I'm de-queueing the script here -- not enqueuing it.

(To be clear .. right now I'm just testing to see if I can successfully de-register the script. I haven't yet tried enqueing a different script.)

- Yvan
egoselfaxisAuthor Commented:
Chris -- am I supposed to just make up my own handle name? Is that what you're saying?

add_action( 'wp_my_own_handle_name, 'remove_scripts' );

- Yvan
Chris StanyonWebDevCommented:
There is no such hook in Wordpress called houzez-custom. That's just a name (handle) your scripts have been given. Just before WordPress outputs the scripts to your page, it will fire it's own built-in hook called wp_print_scripts. The trick here is to do something when Wordpress fires that built in hook. In your case, you want it to run your remove_scripts function:  

// function to remove the scripts
function remove_scripts() {
    wp_dequeue_script( 'houzez-custom' ); // houzez-custom is the name (handle) that was given when it was first enqueued
}

// call the remove_scripts function when WordPress fires it's wp_print_scripts hook
add_action( 'wp_print_scripts', 'remove_scripts' );

Open in new window

egoselfaxisAuthor Commented:
Aha -- that worked, finally (the custom.js file has been successfully deregistered).  Thank you!

Now what would be the proper way for me to enqueue my own/modified custom.js file from within my child theme folder?

I tried adding this line to my child theme's functions.php file .. but I'm now throwing errors on the front end of the site (see below).  Can I perhaps simply this method somehow?

wp_enqueue_script('houzez-custom', get_template_directory_uri() . '/js/custom' . $js_minify_prefix . '.js', array('jquery'), HOUZEZ_THEME_VERSION, true); 

Open in new window


Warning: Use of undefined constant HOUZEZ_THEME_VERSION - assumed 'HOUZEZ_THEME_VERSION' (this will throw an Error in a future version of PHP) in /home/royalpal/staging.royalpalm.com/wp-content/themes/houzez-child/functions.php on line 28

Warning: session_start(): Cannot start session when headers already sent in /home/royalpal/staging.royalpalm.com/wp-content/themes/houzez/framework/classes/Houzez_Compare_Properties.php on line 16

Warning: session_start(): Cannot start session when headers already sent in /home/royalpal/staging.royalpalm.com/wp-content/themes/houzez/framework/classes/Houzez_Compare_Properties.php on line 67
Chris StanyonWebDevCommented:
Cool.

Now that you've dequeued the scripts, to add your own version, add the following to your child function file:

function add_my_scripts()
{
    wp_enqueue_script('my-houzez-custom', 'path/to/your/new/script', array('jquery'), null, true);
}
add_action( 'wp_enqueue_scripts', 'add_my_scripts' );

Open in new window

Similar to before, we're basically saying when WordPress is ready to add the scripts (it fires the wp_enqueue_scripts hook), we want to run our own add_my_scripts() function. This function will then enqueue your new script.

You will need to provide the path to the script as the second argument of the wp_enqueue_script() function.

The code that you just posted up would have re-added the exact same script as you just removed. The reason for the error is because you are referring to a CONSTANT called HOUZEZ_THEME_VERSION that would be set in the Parent functions file. It probably isn't available in the child theme. You also refer to a variable called $js_minify_prefix which may also not be available.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
egoselfaxisAuthor Commented:
Thank you so much.  I've succeeded at overriding the custom.js file with the modified one that's in my child theme folder.  I'm running into another annoying problem, though, .. where my custom.js file is apparently trying to load some variables that are contained within that register-scripts.php file (via the wp_localize_script method). I tried copying over the register-scripts.php file to the same location within my child theme folder, but that isn't working for some reason.  

ReferenceError: HOUZEZ_ajaxcalls_vars is not defined

This error is resulting in one my slideshows on the homepage having gone completely invisible.  Still, I'll go ahead and close this out this thread and award you the points you deserve.  Thanks again for your help!

- Yvan
Chris StanyonWebDevCommented:
Good news Yvan. Pleased you got it working, at least in part.

If you post another question I'll try and take a look if I have some time.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.