parsing CSS in PHP with global variables. WordPress

I have a slight problem which I’m unsure how to fix as I’m a little naive with parsing css files in php. I’m using wordpress and I’m building a feature which I need to apply widths to my elements dynamically.

In theory, in a procedural sense my method should work.

Read More

What I’ve done is in the header file:

global$imageSlider;//global as needed in other files
$imageSlider=new slider();//my class

$imageSlider->add_css();//just an enqueue really.
//wp_enqueue_styles('image_slider_styles',get_template_directory_uri()."/css/imageSlider.css");

Now seeing as my imageSlider.css proceeds my global declaration, I’d imagine the file would be able to use $imageSlider.

The CSS file is parsed in PHP using .htaccess

<FilesMatch ".(css)$">
    AddHandler application/x-httpd-php .css
</FilesMatch>

Which works with local variables. Is parsing this file happening before I’ve declared $imageSlider?

in the CSS file

header("Content-type: text/css; charset: UTF-8");
$pref=$imageSlider->build_css_widths();
//$imageSlider::build_css_widths() returns an array
//The rest of my styles
#imageSlider #sliderHolder{width:<?echo$pref['total'];?>%;}

The class slider() is located in my functions file.

Is there an alternative way or am I missing something?
But it’s returning nothing. 🙁

The error I’m getting is a call to member function on non object which basically means $imageSlider was never declared?

Related posts

Leave a Reply

1 comment

  1. The problem is, your CSS file containing PHP is loaded outside of WordPress, and thus knows nothing about your global variable declared inside of WordPress.

    One common technique, is to simply output the customized properties in the head of the page using wp_head

    function my_style() {
        ?><style type="text/css"><?php
        //Output CSS.
        ?></style><?php
    }
    add_action( 'wp_head', 'my_style' );
    

    Another technique would be to use the AJAX URL, and register an action that will respond with the dynamic CSS.

    $style_url = add_query_arg( array( 'action' => 'my-style' ), admin_url( 'admin-ajax.php' ) );
    wp_enqueue_styles( 'my-style', $style_url );
    
    function my_style() {
        header( 'Content-type: text/css; charset: UTF-8' );
        //Output CSS.
    }
    add_action( 'wp_ajax_my-style', 'my_style' );
    add_action( 'wp_ajax_nopriv_my-style', 'my_style' );
    

    In either case, I strongly recommend separating out the dynamic styles from the static CSS. Parsing the entire CSS file though PHP adds unnecessary load to the server. Also .htaccess-based tricks for parsing CSS as PHP will only work with Apache servers.