How to output wp_enqueue_style() in HTML head instead of footer

I added some actions to wp_enqueue_scripts to load my custom css and js files in the header section by using wp_head(); right before the closing /head tag.

function mytheme_scripts(){
    // Load our main stylesheet
    wp_enqueue_style( 'mytheme-css', get_template_directory_uri() . '/css/styles.min.css', false);
    // Load concatenated vendors JavaScript file
    wp_enqueue_script( 'vendors-js', get_template_directory_uri() . '/js/vendors.min.js');
    // Load our main JavaScript file
    wp_enqueue_script( 'mytheme-js', get_template_directory_uri() . '/js/app.min.js', array( 'vendors-js' ));

}
add_action( 'wp_enqueue_scripts', 'mytheme_scripts', false);

While both *.js files are loaded in the HTML head section the custom *.css file is loaded in the footer of the page (probably triggered by wp_footer()).

I have read about the fact that wp_enqueue_scripts() could be placed anywhere in the source code since any earlier WP version. I've also read that wp_enqueue_script() has a parameter $in_footer to control the output location. However, wp_enqueue_style() doesn't have such an option.

Now, how can I have my custom stylesheet link be placed in HTML head section without hard-coding it into header.php?

Topic wp-enqueue-style wp-head theme-development Wordpress

Category Web


hook into init action on your initial plugin function

add_action('init', array(__CLASS__, 'your_function_within_class'));

and add the function

public static function your_function_within_class()
{
    
    wp_register_style('myfirstplugin-admin-css', '/wp-content/plugins/myfirstplugin/assets/style.css', false);
    
    wp_enqueue_style('myfirstplugin-admin-css');
}

hope this help


You can change the hook to get_footer so files are inserted in the footer

try changing

add_action( 'wp_enqueue_scripts', 'mytheme_scripts', false);

to

add_action( 'get_footer', 'mytheme_scripts', false);

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.