Archived topic
Dynamic styles
3 replies · Started by Mark on March 4, 2022
Hello GB (and BP) and thank you for some great products.
I'm a new user of both GP and GB. Mostly because i love the modular thinking behind it, and how that just makes for some speedy sites :)
A quik question though. I use ACF Blocks and would like to, dynamicly add styles only when a block is used on a page. Nothing new there.
THE QUESTION: After some investigation i understand that GP or GB generate stylesheets according to the blocks used. Are there any way i can filter or hook in to this proces and have my styles from the ACF blocks be loaded with the GB blocks? If no, do you have any info/links on best practise for loading block styles, perhaps on how GP/GB does it?.
Thank you in advance.
Mark
Hi Mark,
Welcome :) GB will only check for its blocks, not others... so i have passed your question onto Tom as he's better placed to advise on the methods we use.
Thank you David.
Hey Mark,
Do these blocks needs CSS built with variables (PHP)? If so, it's not easy but is possible.
First, you need to scan the content for your blocks. This is the function that does it for us in GB: https://github.com/tomusborne/generateblocks/blob/1.4.2/includes/functions.php#L22
Simplified for one block it would look like this:
function myprefix_get_block_data( $content, $data = array(), $depth = 0 ) {
if ( ! is_array( $content ) || empty( $content ) ) {
return;
}
foreach ( $content as $index => $block ) {
if ( ! is_object( $block ) && is_array( $block ) && isset( $block['blockName'] ) ) {
if ( 'my-block/name' === $block['blockName'] ) {
$data['my-block/name'][] = $block['attrs'];
}
if ( 'core/block' === $block['blockName'] ) {
if ( isset( $block['attrs'] ) && is_array( $block['attrs'] ) ) {
$atts = $block['attrs'];
if ( isset( $atts['ref'] ) && ( empty( $data['reusableBlockIds'] ) || ! in_array( $atts['ref'], (array) $data['reusableBlockIds'] ) ) ) {
$reusable_block = get_post( $atts['ref'] );
if ( $reusable_block && 'wp_block' === $reusable_block->post_type && 'publish' === $reusable_block->post_status ) {
$reuse_data_block = parse_blocks( $reusable_block->post_content );
if ( ! empty( $reuse_data_block ) ) {
$data['reusableBlockIds'][] = $atts['ref'];
$data = myprefix_get_block_data( $reuse_data_block, $data );
}
}
}
}
}
if ( isset( $block['innerBlocks'] ) && ! empty( $block['innerBlocks'] ) && is_array( $block['innerBlocks'] ) ) {
$data = myprefix_get_block_data( $block['innerBlocks'], $data, $depth );
}
}
}
return $data;
}
Then you need to call that function to get your data to write your CSS.
We do that here: https://github.com/tomusborne/generateblocks/blob/1.4.2/includes/generate-css.php#L20
You can simplify it a lot since it's only for one block.
Hope this helps! :)