How to force wp_enqueue_style() to display the CSS at the very bottom of the tag

While you can’t directly force wp_enqueue_style() to display the CSS at the very bottom of the tag, you can control the loading order of stylesheets by adjusting the priority parameter of the wp_enqueue_scripts action and the dependency parameter of the wp_enqueue_style() function. This way, you can ensure that your custom CSS is loaded after all other stylesheets and overrides their rules.

Here’s how you can do that:

  1. In your WordPress admin dashboard, go to “Appearance” > “Theme Editor.”
  2. In the right sidebar, locate and click on the “functions.php” file.
  3. Add the following code snippet at the end of the file:
function my_theme_enqueue_custom_styles() {
    // Register your custom stylesheet
    wp_register_style('my-custom-style', get_template_directory_uri() . '/css/my-custom-style.css', array(), '1.0', 'all');

    // Get all registered styles
    global $wp_styles;
    $registered_styles = $wp_styles->registered;

    // Set an empty array for dependencies
    $dependencies = array();

    // Loop through registered styles and add their handles as dependencies
    foreach ($registered_styles as $handle => $style) {
        $dependencies[] = $handle;
    }

    // Enqueue your custom stylesheet with the other styles as dependencies
    wp_enqueue_style('my-custom-style', get_template_directory_uri() . '/css/my-custom-style.css', $dependencies, '1.0', 'all');
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_custom_styles', PHP_INT_MAX);

Replace /css/my-custom-style.css with the path to your custom CSS file.

This code snippet creates a function called my_theme_enqueue_custom_styles() that registers and enqueues your custom stylesheet. The add_action() function has a priority parameter set to PHP_INT_MAX, which is the highest possible priority, making your function run last.

The custom function sets all registered styles as dependencies for your custom stylesheet, ensuring that it is loaded after all other stylesheets.

  1. Click “Update File” to save the changes.

Now, your custom CSS should be loaded after all other styles, allowing it to override other CSS rules.

Remember to always backup your files before making any changes, and test your changes on a staging site or local development environment before applying them to your live site.

Leave a Reply

Your email address will not be published. Required fields are marked *