My parent theme has a script in \includes\js\custom.js, and I am trying to override this from my child theme. I can see from my parent theme that it is en-queued using this code: (I've trimmed some non-relevant lines of wp_enqueue_script() calls.)
function my_deregister_scripts() {
wp_deregister_script( 'jquery' );
wp_enqueue_script('jquery', get_template_directory_uri().'/includes/js/jquery.min.js', false, '1.6.4');
wp_enqueue_script('jquery-custom', get_template_directory_uri().'/includes/js/custom.js', false, '1.0');
if ( is_singular() && get_option('thread_comments') ) wp_enqueue_script( 'comment-reply' );
}
At first , I thought I could simply add some code into my own child functions.php like this:
function custom_script_fix()
{
wp_dequeue_script( 'jquery-custom' );
wp_enqueue_script( 'child-jquery-custom', get_stylesheet_directory_uri() .'/includes/js/custom.js', false, '1.0');
}
add_action( 'wp_enqueue_scripts', 'custom_script_fix' );
but then I read in the codex that nowadays, the child functions.php is run immediately before the parent functions.php. This means that I am dequeueing something that will obly be enqueued again in the parent functions.php. This results in my script being loaded first, followed by the parent script:
So, how would I do this without modifying the parent theme in any way?
Or, you can override an entire function defined in parent theme if it is assigned as a callback to a hook. You remove this filter hook in the child theme functions. php as: add_action( 'init', function() { remove_filter( 'the_content', 'append_thank_you' ); } );
If you're mostly adding custom CSS, then creating a child theme is ideal. But if you're making extensive customizations to the theme's functionality, then you'll be better off creating a parent theme, or selecting an option that has an existing child theme that you can then edit immediately.
In WordPress, there's no such thing as “overriding JavaScript”—in a child theme, or anywhere else. Instead, JavaScript files are enqueued using wp_enqueue_script() . Any enqueued script will run, whether it's in the parent theme or child theme.
By simply registering the script and using the same handle that is being used in the parent theme, it takes precedence. Thus when the parent theme gets around to enqueueing its own version, the handle is already allocated, and it enqueues the override instead.
function custom_script_fix()
{
// use same handle as parent theme to override ('jquery-custom')
wp_register_script('jquery-custom', get_stylesheet_directory_uri() .'/includes/js/custom.js', false, '1.0');
}
add_action( 'wp_enqueue_scripts', 'custom_script_fix' );
The description on wp_enqueue_script()
specifies it won't replace the registered version. You may need to set a lower $priority
on add_action()
to ensure your override script is registered first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With