Skip to content

Instantly share code, notes, and snippets.

@davidwebca
Last active June 24, 2022 00:09
Show Gist options
  • Save davidwebca/135f03e6fbf950e354995d4ac9dd22a8 to your computer and use it in GitHub Desktop.
Save davidwebca/135f03e6fbf950e354995d4ac9dd22a8 to your computer and use it in GitHub Desktop.
Create tmp files for Lazy Block to allow Tailwind CSS to watch for CSS class names and create / purge properly
<?php
/**
* Allows HTML + Handlebars or database-saved PHP code to be
* cached into files so that Tailwind CSS can detect and watch
* for classes used and purge unecessary ones.
*
* @see https://github.com/nk-crew/lazy-blocks/
* @see https://github.com/nk-crew/lazy-blocks/issues/246
*/
add_action('save_post', function($post_ID, $post, $update) {
if($post->post_type == 'lazyblocks') {
// Account for both contexts
$contexts = ['frontend', 'editor'];
// Get output method
$output_method = get_post_meta($post_ID, 'lazyblocks_code_output_method', true);
// Get block slug to create legible tmp file name
$block_slug = get_post_meta($post_ID, 'lazyblocks_slug', true);
// Cache folder name
$cache_folder = get_template_directory() . '/lzb-storage';
// Only save tmp file if php or handlebars
if($output_method == 'php' || $output_method == 'html') {
foreach($contexts as $context) {
$context_code = get_post_meta($post_ID, "lazyblocks_code_{$context}_html", true);
// Create the cache folder if it doesn't exist
if(!is_dir($cache_folder)) {
mkdir($cache_folder);
}
// Sometimes, editor side doesn't exist so we simply check if it's not empty before
if(!empty(trim($context_code))) {
file_put_contents(get_template_directory() . "/lzb-storage/{$block_slug}-{$context}.tmp", $context_code);
}
}
}
}
}, 10, 3);
/**
* Add the folder and tmp files to the content
* declaration in your tailwind.config.js file
*/
module.exports = {
content: [
'./lzb-storage/*.tmp' // Add this
],
safelist: [
],
theme: {
extend: {}
},
plugins: [],
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment