How do I get my PHP variable to echo inside my CSS stylesheet?

OK, so I’m building a WordPress theme that will allow my client to assign a colour to each category. However this is proving to be quite difficult when it comes to making the stylesheet read the code.

I’m using this code

Read More
.thumbnail-section {
    width: 100%;
    height: 450px;
    overflow: hidden;
    background: <?php echo $category_color; ?> ;
}

but for some reason the PHP isn’t being noticed.

I’ve also placed the following code at the top of the stylesheet and changed the .css extension to .php

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

EDIT: Sorry, I forgot to mention. The variable is being defined by the category. Here’s the code:

<?php
            $category = get_the_category();
            $the_category_id = $category[0]->cat_ID;

            if(function_exists('rl_color')){
                $rl_category_color = rl_color($the_category_id);
            }
        ?>

Related posts

3 comments

  1. multiple ways

    one is Set .htaccess:

    AddType application/x-httpd-php .css
    

    and echo the data in .css file.

  2. Ensure that the file has a name with ‘style’ in it, and leave the extension as .css.

    Then go to your .htaccess file and add this into it to force it to be executed:

    <FilesMatch "^.*?style.*?$">
        SetHandler php5-script
    </FilesMatch>
    
  3. It will work, assuming the structure is something like this and the file extension is php:

    <?php
        header("Content-type: text/css; charset: UTF-8");
        $category_color="blue";
    ?>
    .thumbnail-section {
        width: 100%;
        height: 450px;
        overflow: hidden;
        background: <?php echo $category_color; ?> ;
    }
    

    Check how you set the $category_color.

    There’s a file on my server with the above contents.

Comments are closed.