Dequeueing a JavaScript or CSS file in a WordPress child theme is a common task for developers who want to remove unnecessary or conflicting scripts or styles added by a theme or plugin. Here’s a quick guide to help you achieve this.
Why Dequeue Scripts or Styles?
Sometimes, a parent theme or plugin includes scripts or styles that you don’t need or that conflict with your customizations. Dequeueing them helps:
- Improve site performance by reducing HTTP requests.
- Avoid style or script conflicts.
- Simplify your customizations.
Steps to Dequeue Scripts or Styles
Follow these steps to dequeue JavaScript or CSS in your WordPress child theme:
1. Identify the Handle of the Script or Style
Each script or style enqueued in WordPress is registered with a unique handle. You need this handle to dequeue it.
- To find the handle, check the source code or developer documentation of the theme/plugin.
- Alternatively, use the following PHP snippet to list all enqueued scripts and styles:
add_action('wp_enqueue_scripts', function() {
global $wp_styles, $wp_scripts;
echo '<!-- Styles -->';
foreach($wp_styles->queue as $style) {
echo $style . '<br>';
}
echo '<!-- Scripts -->';
foreach($wp_scripts->queue as $script) {
echo $script . '<br>';
}
});
Visit your website, view the page source, and look for the handles.
2. Use wp_dequeue_script or wp_dequeue_style
Once you have the handle, dequeue the script or style in the functions.php file of your child theme.
Example:
function my_child_theme_dequeue_scripts() {
// Dequeue a JavaScript file
wp_dequeue_script('example-js-handle');
// Dequeue a CSS file
wp_dequeue_style('example-css-handle');
}
add_action('wp_enqueue_scripts', 'my_child_theme_dequeue_scripts', 20);
3. Ensure Proper Hook Priority
Sometimes, the script or style is enqueued later in the load order, so your dequeue action must run after it has been enqueued. Use a higher priority (e.g., 20 or 99) for your add_action.
4. Test Your Changes
After adding the dequeue function, clear your site’s cache and test:
- Open your website.
- Check if the script or style is removed using the browser’s developer tools.
Example Use Case
Suppose you want to remove the Google Maps script (imic_google_map) added by a parent theme or plugin.
function my_child_theme_remove_google_maps() {
if (!is_admin()) { // Ensure it only affects the frontend
wp_dequeue_script('imic_google_map');
}
}
add_action('wp_enqueue_scripts', 'my_child_theme_remove_google_maps', 20);
Notes
- Don’t Dequeue Essential Files: Be cautious not to remove scripts or styles essential for your site’s functionality or layout.
- Use Conditional Logic: Target specific pages or areas where the script/style should be removed.
if (is_page('contact')) { // Example: Remove only on the Contact page
wp_dequeue_script('example-js-handle');
}
By following these steps, you can easily dequeue unwanted scripts or styles in your WordPress child theme, enhancing your site’s performance and maintainability.