Support

Account

Home Forums General Issues Track specific field update and generate dynamic CSS

Unread

Track specific field update and generate dynamic CSS

  • Track specific field update and generate dynamic CSS

    I’m working on a festival website and the client wants the ability to change the background and text colour of the website each year.

    Currently, I’ve set up a function that will grab the values of 3 custom fields from the home page and dynamically generates a CSS file.

     // Inside functions.php	
        function generate_custom_css() {
    	    $ss_dir = get_stylesheet_directory();
    	    ob_start();
    	    require_once($ss_dir . '/library/css/custom.php');
    	    $css = ob_get_clean();
    	    file_put_contents($ss_dir . '/library/css/custom.css', $css, LOCK_EX);
     	}
    	add_action('acf/save_post', 'generate_custom_css', 20);
    // Inside custom.php
    
    	$year = get_field('festival_year', $home_id);
    	$background = get_field('festival_bg_colour', $home_id); 
    	$accent = get_field('festival_accent_colour', $home_id);
    	
    	echo '.festival-'.$year.'{ 
    	background-color: '.$background.'!important; 
    	color: '.$accent.'!important; 
    	}';

    The problem is that if any page / post on the website is updated, the generate_custom_css() function will execute every time. Which slows down the website.

    I want to setup a boolean function

    acf_field_updated($field_name, $page_id)

    that tracks if any of the 3 fields on the home page have been updated, and outputs a true-false. So the code would be something like this:

     function generate_custom_css() {
    		if ( acf_field_updated('festival_year', $home_id) == 'true' || acf_field_updated('festival_bg_colour', $home_id) == 'true' || acf_field_updated('festival_accent_colour', $home_id) == 'true') {
    		    $ss_dir = get_stylesheet_directory();
    		    ob_start();
    		    require_once($ss_dir . '/library/css/custom.php');
    		    $css = ob_get_clean();
    		    file_put_contents($ss_dir . '/library/css/custom.css', $css, LOCK_EX);
     		}
     	}
    	add_action('acf/save_post', 'generate_custom_css', 20);

    I’ve read the documentation and looked through the forums and I believe I should probably hook into update_value, but I can’t quite figure out how to make this work.

    I would be very grateful for any help you can provide.

Viewing 1 post (of 1 total)

The topic ‘Track specific field update and generate dynamic CSS’ is closed to new replies.