Support

Account

Home Forums General Issues PHP as CSS with ACF field

Solving

PHP as CSS with ACF field

  • PHP as CSS with acf field

    I created a PHP file(dynamic.php) that will read the CSS. In order to that..

    I added this code:

    <?php
        header('Content-Type: text/css');
    ?>

    But inside the php file, I want to get the value from the field..

    for_example

    a {
        color: <?php the_field('a_href_color', $post->ID ); ?>;
        text-decoration: none;
    }

    and I got this error in the php file: (note I used the_field and get_field if one of the function works)

    <b>Fatal error</b>: Uncaught Error: Call to undefined function get_field() or the_field()

  • You cannot do this because nothing in WP is loaded for the CSS file.

    You need to use admin_ajax.php to load a dynamic CSS file.

    https://bappi-d-great.com/how-to-write-dynamic-css-in-a-php-file-in-wordpress/

  • I’ve used the below which grabs values from an option page, then creates a CSS file and enqueues it:

    
    ###################################################
    # Create Custom CSS
    ###################################################
    function acf_generate_options_css() {
    	$ss_dir = get_stylesheet_directory();
    	ob_start(); // Capture all output into buffer
    	require($ss_dir . '/inc/custom-styles.php'); // Grab the custom-style.php file
    	$css = ob_get_clean(); // Store output in a variable, then flush the buffer
    	file_put_contents($ss_dir . '/css/custom-styles.css', $css, LOCK_EX); // Save it as a css file
    	
    }
    add_action( 'acf/save_post', 'acf_generate_options_css', 20 );
    

    I then enqueue the script:

    
    function acf_enqueue_scripts() {
        wp_enqueue_style( 'custom-theme-css', get_template_directory_uri() . '/css/custom-styles.css' );
    }
    add_action( 'wp_enqueue_scripts', 'acf_enqueue_scripts', 99 );
    

    And custom-styles.php looks like this:

    
    $colour_name = get_field('colour_name','option');
    $select_colour = get_field('select_colour','option');
    .bg-colour-<?php echo str_replace(" ","-",strtolower($colour_name)); ?> {
        background-color: <?php echo $select_colour; ?>;
    }
    

    Not sure if that helps at all?

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

You must be logged in to reply to this topic.