WooCommerce loads frontend scripts and styles in class-wc-frontend-scripts.php
file, and there can be found how the scripts are registered, enqueued, localized and dependencies.
The preferred place to enqueue scripts in Wordpress is the wp_enqueue_scripts
action hook, because that is the moment after Wordpress is fully loaded but before any output is made. And also I like to enqueue all my related script and styles in one section of code.
When you want to completely remove some scripts, calling either wp_deregister_script()
or wp_dequeue_script()
is enough. But sometimes if want to make some changes and leave the existing dependencies, variables and localization there is a problem because plugins are loaded before themes. So enqueue functions will not work as you would expect. Simple wp_dequeue_script() => wp_enqueue_script()
will not work, wp_deregister_script() => wp_register_script
() will work, but localized data will be lost.
This can be solved by working directly with $wp_scripts
global object that contains and manages all the scripts loaded through wp_enqueue_script()
or registered with wp_register_script()
:
add_action( 'wp_enqueue_scripts', 'load_theme_scripts' );
function load_theme_scripts() {
global $wp_scripts;
$wp_scripts->registered[ 'wc-add-to-cart' ]->src = get_template_directory_uri() . '/woocommerce/js/wc-add-to-cart.js';
}