I have my style.php
file looking like this.
<?php header('Content-Type: text/css');?>
#div{
background:<?php echo get_option('bgcolor');?>;
}
This does not work, but when I do this it works.
<?php header('Content-Type: text/css');?>
#div{
background: <?php echo 'blue';?>;
}
What would be the problem?
This is the mainfile.php
<?php
function test(){
global get_option('bgcolor');?>
<input type="text" id="bgcolor" name="post_popup_settings[bgcolor]" value="<?php echo get_option('bgcolor');?> " />
<?php
}
add_action('admin_head','test');
This is actually in the admin section.
WordPress functions are available only if WordPress is loaded. If you call your
style.php
directly you cannot use a WordPress function.One simple way to load WordPress for your PHP driven stylesheet is to add an endpoint to WordPress: a custom, reserved URL where you load your template file.
To get there you have to:
Register an endpoint on
'init'
withadd_rewrite_endpoint()
. Letâs name it'phpstyle'
.Hook into
'request'
and make sure the endpoint variable'phpstyle'
is not empty if it is set. Read Christopher Davisâ excellent A (Mostly) Complete Guide to the WordPress Rewrite API to understand whatâs going on here.Hook into
'template_redirect'
and deliver your file instead of the default template fileindex.php
.To keep things short I combined all three simple steps in one function in the following demo plugin.
Plugin PHP Style
Install the plugin, visit
wp-admin/options-permalink.php
once to refresh the rewrite rules, and add astyle.php
to your theme.Sample
style.php
Now visit
yourdomain/phpstyle/
. Output:But if you go to
yourdomain/phpstyle/blue/
the output is:So you can use the endpoint to deliver different stylesheets with one file depending on the value of
get_query_var( 'phpstyle' )
.Caveat
This will slow down your site. WordPress has to be loaded two times for each visit. Donât do it without aggressive caching.
You could do this by loading the output via
admin-ajax.php
, but a better approach to that is to use WordPressSHORTINIT
constant so you can load just what functions you need, but you will need to find and loadwp-load.php
to do this:At this point you will need to be sure include whatever other
wp-includes
files you need to get your theme options – which will vary depending on your how you are saving and thus accessing those. (You will probably need to add more to this list so that you do not get fatal errors – but as you are going, the fatal errors will tell you which files you need to add.) eg.Then once you have all the functions you need, you can output the CSS using those functions… eg.
Then you can enqueue the file as normal, for example: