Dynamic CSS for ACF Flexible Content – loop skips first row?

Using Advanced Custom Fields Pro plugin. I am generating a dynamic CSS sheet for options selected in flexible content fields. I have an acf-css.php sheet:

<?php
header(‘Content-type: text/css’);

if( have_rows(‘flexible_content_field_name’) ):
while ( have_rows(‘flexible_content_field_name’) ) : the_row();

if( get_row_layout()) :
while(get_row_layout()) : the_row();

$background_color = get_sub_field(‘background_color’);
$id = get_the_ID();
$title = get_sub_field(‘title’) . ‘-‘ . $id; ?>

$title .wrapper {
<?php if($background_color) : echo ‘background-color:’ . $background_color . ‘; ‘; endif; ?>
}

<?php

endwhile;
endif;

endwhile;
endif;

?>

Which then creates a css sheet via this function (originally found: https://support.advancedcustomfields.com/forums/topic/acfphp-in-css/):

function generate_options_css() {
$ss_dir = get_stylesheet_directory();
ob_start(); // Capture all output into buffer
require($ss_dir . ‘/styles/acf-css.php’); // Grab the php file
$css = ob_get_clean(); // Store output in a variable, then flush the buffer
file_put_contents($ss_dir . ‘/styles/acf-css.css’, $css, FILE_APPEND | LOCK_EX); // Save it as a css file

}
add_action( ‘acf/save_post’, ‘generate_options_css’, 20 ); //Parse the output and write the CSS file on post save

This works GREAT, except that it always skips over the first row in my flexible content field and appends an empty value at the end of the new CSS sheet. For example, if I have 5 rows in my flex content field, it will take the values from the last 4 and create the CSS as anticipated (so 4 entries for 4 rows). It then creates a 5th entry, which does not get any values. For example:

#unique-title2-12345 .wrapper {
background: red;
}
#unique-title3-12345 .wrapper {
background: blue;
}
#unique-title4-12345 .wrapper {
background: green;
}
#unique-title5-12345 .wrapper {
background: yellow;
}
#-12345 {
.wrapper {
}
}

Any ideas/help/thoughts on this strategy in general would be very appreciated!!

Read more here:: Dynamic CSS for ACF Flexible Content – loop skips first row?

Leave a Reply

Your email address will not be published. Required fields are marked *