functions.php inject inline css

I am trying to inject a inline style css to my body element via the functions.php file.
It needs to be inline, because I am using a ACF to let the user change the image.

This should be the result:

<body style="background-image: url('<?php the_field('background'); ?>');">

I read about the wp add inline style, but i couldn’t figure it out.

Update:
Here is the function I tried:

function wpdocs_styles_method() {
    wp_enqueue_style('custom-style', get_stylesheet_directory_uri() . '/body.css'
    );
        $img = get_theme_mod( "<?php the_field('background') ?>" );
        $custom_css = "body {background-image: {$img}";
        wp_add_inline_style( 'custom-style', $custom_css );
}
add_action( 'wp_enqueue_scripts', 'wpdocs_styles_method' );

I did load a body.css to tried to add the inline css. But it didn’t work – maybe this isn’t the right approach at all?

3 s
3

The easiest way I’ve seen is to echo it where you need it:

function inline_css() {
  echo "<style>html{background-color:#001337}</style>";
}
add_action( 'wp_head', 'inline_css', 0 );

Since 2019 you can also add styles inline inside the body, shown here without using echo:

function example_body_open () { ?>
  <style>
    html {
      background-color: #B4D455;
    }
  </style>
<?php }
add_action( 'wp_body_open', 'example_body_open' );

The benefit here is you get better syntax highlighting and do not need to escape double-quotes. Note this particular hook will only work with themes implementing wp_body_open hook.

Leave a Comment