1. Home
  2. Web Development
  3. How to enqueue inline style without a stylesheet in WordPress

How to enqueue inline style without a stylesheet in WordPress

Share

As developers, we often need to add a new inline style to our WordPress theme without having to enqueue a full stylesheet file. How do we do it?

But first, let’s take a step back. In WordPress we mainly have two options if we need to add new styles:

  • we can use the wp_enqueue_style function to enqueue a stylesheet;
  • we can use the wp_add_inline_style function to enqueue an inline style.

But what happens if we want to enqueue an inline style in WordPress without having to add a stylesheet file? The wp_add_inline_style function will not work as expected. Indeed, it will not add the inline style to the <head> of the page unless we have already enqueued a stylesheet file.

The first parameter of the wp_add_inline_style function is the name of the stylesheet to add the extra styles to, and the second parameter is a string that contains the CSS styles that we want to add in the inline style tag. The stylesheet name is required and the style needs to be in the WordPress queue, or the inline style won’t be included.

But let’s see a practical example. The following code shows how we would normally use wp_add_inline_style to enqueue an inline style after a stylesheet file:

<?php
wp_enqueue_style( 'my-stylesheet', get_stylesheet_uri() );
wp_add_inline_style( 'my-stylesheet', 'body { background-color: #f00; }' );
?>

To solve our problem we have two options:

  1. add the inline style to the wp_head action hook;
  2. use a dummy stylesheet file

Let’s see these two options more in-depth.

Option 1: Add the inline style to the `wp_head` action hook

To add the inline style to the wp_head action hook we won’t use the wp_add_inline_style. The approach is to create a function that will return a string containing the inline style and include it in the wp_head action hook.

Let’s see the following example:

<?php
function my_custom_styles()
{
    echo '<style>body { background-color: #f00; }</style>';
}
add_action('wp_head', 'my_custom_styles', 100);
?>

This simple piece of code does its job.

Option 2: Use a dummy stylesheet file

Another option is to use a dummy stylesheet file. This method is more flexible and allows us to add the inline style without the need of using the apply_filters function.

Let’s see this other example:

<?php
wp_enqueue_style( 'my-stylesheet', false );
wp_add_inline_style( 'my-stylesheet', 'body { background-color: #f00; }' );
?>

That’s it! Now we have an inline style without the need of having a stylesheet file.

If you like our post, please share it: