I am using the following function, which works fine, in order to provide a minimal output of HTML at a WordPress installation of mine:

add_action( 'template_redirect', 'test' );

function test()
<!doctype html>
<html lang="en-US">
<link rel='stylesheet' type='text/css' href='<?php echo home_url() ?>/wp-content/plugins/myplugin/style.css'>

It does exactly what I want, but I'm considering of loading my style the proper way, using wp_enqueue_style.

Since im not loading wp_head, I tried it and it seems not possible on template_redirect level.

Is there any way to enqueue my style on my function without hardcoding it?


The reason to use wp_enqueue_style is to allow WordPress to manage dependencies between stylesheets. Since you're only outputting a barebones page here, there really is no point to use it.

That said, if you look at the hook order, you see that template_redirect is actually called quite late in the process, just before the scripts and styles are enqueued, but before wp_head. As you can see in the list of default filters/actions (and as you found out) the scripts and styles are only printed at the wp_head stage, with this line of code:

add_action( 'wp_head', 'wp_print_styles', 8 );

So, if you want to enqueue a file at the template_redirect stage you will have to cheat by running both the enqueueing and printing process early. That is not too difficult, though, because WordPress has already been fully loaded at this stage. All functions are available, including the styles class. In stead of your line <link rel = ... > you could execute the styles chain of command early, like this:

wp_styles (); // initialize the styles object
wp_enqueue_style ('my_handle', 'path-to-file'); // make the file ready for printing
wp_print_styles (); // print the enqueued style

I didn't test this, because it doesn't really make sense, but I hope you get the point.

  • Thank you for the explanation. wp_styles works, however, it brings the emoji's style aswell in my head ( pastebin.com/J2inxNDt ) . Any ideas on how to exlude it? – JohnnyBratsoni May 4 '19 at 13:01
  • remove_action( 'wp_print_styles', 'print_emoji_styles' ); seems to do the trick. Thanks. – JohnnyBratsoni May 4 '19 at 13:05
  • glad it worked for you – cjbj May 4 '19 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.