In WordPress I am using ACF to create a page builder using flexible content fields. For each component I’m manually creating _component-name.scss
and appending it to my main SCSS file. This is fine but prone to error.
Given this I was looking at the ACF filters and saw that there is acf/update_field
so my intention was to say when the flexible content field is updated loop through the layouts array and create scss files using the layout name, as then I couldn’t forget.
An issue I’m having is that the creation is all fine, but when you rename a layout I really want to update the name of the corresponding scss file, however, I don’t know what the name previously was.
Here is my attempt, which handles creation okay, but I’m stumped on renaming.
add_filter('acf/update_field', 'create_css_files', 10, 1);
/**
* When ACF Fields are saved, check to see if it was the page builder,
* if it was, attempt to create a new scss file for any new elements within our page builder.
* Note that get_stylesheet_directory gets the root of the current theme.
*
* @param [type] $field
*
* @return void
*/
function create_css_files($field)
{
if ($field['name'] == 'page_builder_elements') {
foreach ($field['layouts'] as $layout) {
$name = $layout['name'];
// Only allow letters, numbers, hyphens and underscores
$clean_name = preg_replace('/[^A-Za-z0-9_-]/', '', $name);
// Replace underscores with hyphens in the layout name
$clean_name = str_replace('_', '-', $clean_name);
$file_path = get_stylesheet_directory() . '/resources/styles/scss/_' . $clean_name . '.scss';
$directory = dirname($file_path);
if (!file_exists($directory)) {
mkdir($directory, 0755, true);
}
if (!file_exists($file_path)) {
$file_handle = fopen($file_path, 'w');
fclose($file_handle);
}
$import_directive = "@import 'scss/$clean_name';" . "n";
$base_stylesheet_path = get_stylesheet_directory() . '/resources/styles/app.scss';
file_put_contents($base_stylesheet_path, $import_directive, FILE_APPEND);
}
}
return $field;
}
2
Answers
I don't know if I'm happy with it, but this is what I ended up with.
Probably the simplest way to manage this is to analyze the files that exist in the directory, and the files that are not in the list of layout names, then delete those files.