Access to the global variable in "CSS" (style.php)

I am making a CSS style.php file, so I can use some dynamic variables in CSS as part of a Wordpress installation:

<?php header("Content-type: text/css"); ?> 

etc.

How to access a global variable from a style.php file or pass a variable to it?

The code I'm trying to work in CSS is similar to

 $maincolor = $cap->br_main_color; 

also:

  • Ignore the caching issue. This is just a personal project.
  • Passing a variable in a link to a stylesheet is too complicated for this (in my opinion).

EDIT: as a little more explanation: what I am doing is generating a whole theme based on several colors and calculating shades for hover effects, etc. About 50% of the styles have some PHP in them. Everything works fine if I manually enter colors in style.php, but I try to make it even easier for less skilled people and use a color picker.

+6
php global-variables wordpress
source share
2 answers

To access the wordpress features, you need to include the following lines on top of the style.php file.

 define('WP_USE_THEMES', false); require('./wp-blog-header.php'); 

The first line tells wordpress not to start process-related processes, and the second line starts the wordpress mechanism. After that, you will get access to the wordpress functions and global variables.

+3
source share

Here's an alternative solution for embedding php in the Wordpress.css stylesheet (a utility that I'm not sure about) that does not require manipulation of the Wordpress core.

Just create an inline CSS php file in the theme directory containing regular code:


embedded_style.php

 /* define document as css*/ <?php header("Content-type: text/css"); ?> /* Example php variable declaration and function call */ <?php $body_color = get_color(); ?> /* Begin php embedded css code below here */ body { background: none; color: <?php echo $body_color ?>; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 10pt } 

Then import this dynamic file into your style.css themes so you don't have to change the core of Wordpress.


style.css

 /* Theme Name: Mytheme Version: 1.0 Description: This theme has php embedded css Author: You */ @import url(embedded_style.php); /* Normal CSS below as required */ 

my 2 cents

The genesis of this snippet was an attempt to allow directory changes when importing css from the parent theme into my child. I did not like the idea of ​​changing the core wordpress files, however, since most functions / hooks are not defined in runtime for style.css, in order to break the call, an alternative method had to be found. In the end, I did not use this for the same reasons that I could not interrupt the file call (it is too early to use convenient Wordpress constants, etc.), However, I hope it is useful to someone else.

+4
source share

All Articles