Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create inline CSS in a WordPress PHP file without referencing to an external CSS file?

Tags:

css

php

wordpress

I want to enqueue a string of CSS directly from a Wordpress plugin. I don't want to load it from an external file, and I don't want to debate why this is the write or wrong thing to do, I just want to know if it is possible.

In other words, I know I can do this:

wp_register_style('myStyleSheet', 'my-stylesheet.php');
wp_enqueue_style( 'myStyleSheet');

But I don't wan't to.

What I want to do is something like this (pseudocode):

$number = get_option('some_width')/2;
$css = " .divbox { width: $number; } ";
wp_register_style('myStyleSheet', $css);
wp_enqueue_style( 'myStyleSheet');

I read the wp codex for wp_register_style() and it doesn't seem possible. Anyone have a suggestion?

like image 519
ethanpil Avatar asked Jan 09 '13 02:01

ethanpil


People also ask

How do I add an inline CSS in WordPress?

Need for Inline or Internal CSS in WordPress For the second solution of adding CSS, you have two options: Insert the CSS block by hard-coding the CSS style within the header file. Compile CSS and use WordPress enqueue function to insert inline style.

Which CSS is best inline or external?

The main difference between inline CSS and external CSS is that inline CSS is processed faster as it only requires the browser to download 1 file while using external CSS will require downloading HTML and CSS files separately.

Can you use CSS with PHP?

You can add css styling to a page generated by php just the same as you would an ordinary html page. Typically you would link to a style sheet in the head section, or put the styling in <style> tags within the head.


1 Answers

Well that was silly of me. I found the answer a few minutes later. Desperation is a good motivator! :)

The trick is not to use wp_register_style() and wp_enqueue_style()

Here is what I did:

function myStyleSheet() {

  global $value;
  $num = $value/2;

  echo '
       <style type="text/css">
            .divbox { width: '.$num.'; }    
       </style>
    ';
}
add_action( 'wp_print_styles', 'myStyleSheet' );

Still, maybe there is a better way?

like image 151
ethanpil Avatar answered Sep 30 '22 23:09

ethanpil