Home Forums Front-end Issues ACF/PHP in CSS



    • gab1982

    • June 28, 2016 at 11:32 pm

    I have been trying to create a stylesheet php page like this–net-6409 but using acf values but I cant get it to work with ACF fields.

    an example of some of my css code is:

    .divider .wrapper::before {
    	background-image: url("<?=the_field('section_bg_image_overlay','options')?>");

    and at the top of my stylesheet php page which is called ‘main.css.php’ I have:

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

  • When it comes to WP, you can’t get values from the site by just loading a PHP file. You need to also load a lot of the WordPress code. The best way to do this is by using the admin-ajax script. I posted the basics of a solution for this about 2 years ago here

  • Thank you John for your reply, however I found another solution although its still early days of testing yet:

    I managed to create a file called main.css.php where I put only my css code and the ACF php code and then added this to my functions file:

    function generate_options_css() {
        ob_start(); // Capture all output into buffer
        require_once dirname( __FILE__ ) . '/main.css.php';
    	$css = ob_get_clean(); // Store output in a variable, then flush the buffer
        file_put_contents(dirname( __FILE__ ) . '/', $css, LOCK_EX); // Save it as a css file
    	wp_enqueue_style( 'main_css', get_template_directory_uri() . '/' );
    add_action( 'wp_enqueue_scripts', 'generate_options_css' );
  • That’s an interesting possibility. The main problem that I see is that you’ll be regenerating this css file on every page load. I would look into some way to do some type of file caching or something so that it’s only regenerated when it needs do be. Not sure how you’d know that.

  • Perhaps I could use a session and set the timeout for the session, then check to see if the session is set, if not to generate the file, I will look closer tomorrow and update here accordingly.

  • It’s not a necessity, I guess it would depend on how much you php file needs to interact with the DB.

  • Hi @gab1982 did you find a way not to regenerate the css file each time ?
    Thanks a lot

  • This works great without regenerating css file on each page load:

  • Hi @andrestobar I just went through that link, followed it step by step. It works up until the point that I add my custom field parameters. When I add the custom field parameter, it seems to render the file unreadable. Have you had this happen before?

Viewing 9 posts - 1 through 9 (of 9 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.