In a typical wordpress flow, plugins are loaded before the theme, and in case of child theme, child theme is loaded before the parent theme, specifically, functions.php
file of a child theme is included before the functions.php of a parent. So, wp_enqueue_scripts
actions are stacked, and later execution in the that order, unless the priority of actions is defined diferently that default value ( 10 ). The problem here is that you are trying to dequeue script that has not yet been enqueued.
To remove the script added by parent, raise the priority of wp_enqueue_scripts
action of child theme to value higher than value defined in parent theme action.
// get_template_directory_uri(), if used in child theme, the parent theme directory URI will be returned,
// use get_stylesheet_directory_uri() to get the child's theme directory uri
add_action( 'wp_enqueue_scripts', 'child_theme_enqueue_scripts', 11 );
function child_theme_enqueue_scripts()
{
wp_dequeue_script( 'parent-theme-script' );
wp_enqueue_script( 'child-theme-script', get_stylesheet_directory_uri() . '/js/script.js' );
}
To replace the script, for example, you want to make some changes and leave the existing dependencies and localization there are two ways.
Use wp_enqueue_script
with the same handle
name, due the fact that if you try to register or enqueue an already registered handle, the new parameters will be ignored, useful if the script is later localized by parent to keep the localized data.
// default priority 10
add_action( 'wp_enqueue_scripts', 'child_theme_enqueue_scripts' );
function child_theme_enqueue_scripts()
{
wp_enqueue_script( 'parent-theme-script', get_stylesheet_directory_uri() . '/js/script.js' );
}
Use global $wp_scripts
object to modify only required properties, for example, change only src
property of already enqueued or registered script.
// priority 11
add_action( 'wp_enqueue_scripts', 'child_theme_enqueue_scripts', 11 );
function child_theme_enqueue_scripts()
{
global $wp_scripts;
$wp_scripts->registered[ 'parent-theme-script' ]->src = get_stylesheet_directory_uri() . '/js/script.js';
}
The fact that child theme is loaded first is quite practical since the use of child theme is not to replace, but more as addition to the main theme.