stemon
stemon

Reputation: 651

Wordpress Child Theme Enqueue and Dequeue and Localize

I am trying to enqueue an edited js file from my child theme and dequeue the original one from the parent. It should be simple, however, the parent theme is calling a function where all enqueues are made. I managed to enqueue it but not to dequeue. In addition, the original enqueue is followed by wp_localize_script() function.

If I copy the whole function to my child it works, but I am looking for a cleaner and better way to achieve that.

Here is how the original code is set up (Parent Theme):

In function.php this function is called

        add_action('wp_enqueue_scripts', 'wpestate_scripts'); 

The wpestate_scripts function is found in another file, css_js_include.php

function wpestate_scripts() { 

// A bunch of files being enqueued and some variables being assigned

 wp_enqueue_script('wpestate_property', trailingslashit( get_stylesheet_directory_uri() ).'js/property.js',array('jquery','wpestate_control'), '1.0', true);   
        wp_localize_script('wpestate_property', 'property_vars', 
            array( 
                // Variables being localized
              )
        );

 }

I have already added wp_dequeue_script('wpestate_property') and wp_deregister_script('wpestate_property') to my child function.php. And it did not work.

Any help is appreciated.

Upvotes: 0

Views: 557

Answers (1)

Xhynk
Xhynk

Reputation: 13870

You need to make sure the function you're calling is fired after the script is enqueued by the parent. Typically this is done by adding a high integer value to the $priority argument for add_action().

add_action( 'wp_enqueue_scripts', 'modify_wpestate_scripts', 99 );
function modify_wpestate_scripts() {
    wp_dequeue_script('wpestate_property');

    // Enqueue your custom script instead
    wp_enqueue_script( 'custom-wpestate_property', 'custom-wpep.js', [], '1.0', true );
    wp_localize_script('custom-wpestate_property', 'property_vars', 
        array( 
            // Variables being localized
          )
    );
}

This adds it to the same action hook (wp_enqueue_scripts) as the parent function, but the priorty is set to 99 so it runs later (the default priority is 10).

Upvotes: 2

Related Questions