0

I would like to read from a .css file and inject it as an inline style in wp_head. it's possible?

i've tried this "Add inline css to theme" solution but it doesn't do what I expect because I expect all the style to be injected into

<style> [mystile.css] </style>

and not

<link href="[mystile.css]">

2 Answers 2

1

You need to add your css to wp_head. In order to do so, you need to get your dynamic CSS first, load in into a variable and then add that variable to the head output. Just like so:

(This code can go into your functions.php, plugin file or somewhere else in your theme, make sure you include this code in a file where it can be called properly)

<?php

  function so_output_dynamic_css() {
    // do some stuff to get your CSS here..
    $some_dynamic_css = "body {background: green;}";
    ?>
    <style type="text/css" id="so-dynamic-css">
         <?php echo $some_dynamic_css; ?>
    </style>
  <?php }
  add_action('wp_head', 'so_output_dynamic_css');
1
  • 1
    it's not exactly my problem ... I don't have a dynamically generated css, I have to get it from a file that was compiled by sass. In addition is more correct to use wp_add_inline_style()
    – Erik
    Commented Jul 23, 2019 at 10:58
1

I found a solution to include a css file without using "file_get_contents()" since it might require php.ini edits (allow_url_fopen). in other hands wp_add_inline_style() needs a registered style to be outputted and, in this case, i can't use it because this is the above the fold style (the rest were loaded into the footer).

as the @user3135691 had pointed out you need to have a variable all the css and then append it to the head.

my solution is:

function inject_css_style() {

  // get the acf.css file and store into a variable
  ob_start();
  include 'wp-content/themes/my-theme/inline.css';
  $atf_css = ob_get_clean();

  // return the stored style
  if ($atf_css != "" ) {
    echo '<style id="inline-css" type="text/css">'. $atf_css . '</style>';
  }
}
1
  • Thanks for sharing the solution later on :-) good job. Commented Jul 23, 2019 at 20:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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