Skip to content

Instantly share code, notes, and snippets.

@SteveRyan-ASU
Created December 5, 2022 17:45
Show Gist options
  • Save SteveRyan-ASU/ba592995849a80345fc5dc63a12ca82a to your computer and use it in GitHub Desktop.
Save SteveRyan-ASU/ba592995849a80345fc5dc63a12ca82a to your computer and use it in GitHub Desktop.
ACF Blocks: Render block spacing string for inline style
/**
* Given an $block object from an ACF block for gutenberg,
* This will return a string of CSS inline values suitable for
* inclusion in the block output in PHP.
*
* @param mixed $block
* @return $style as string
*/
function acf_blocks_calculate_spacing($block) {
$style = '';
$padding = array();
$margin = array();
if (isset($block['style']['spacing']['padding'])) {
$padding = $block['style']['spacing']['padding'];
foreach ($padding as $rule => $value) {
if ( str_starts_with( $value, 'var:') ) {
$var_position = strrpos($value, '|');
$variable = substr($value, $var_position );
$style .= 'padding-' . $rule . ':var(--wp--preset--spacing--' . $variable . '); ';
} else {
$style .= 'padding-' . $rule . ':' . $value . '; ';
}
}
}
if (isset($block['style']['spacing']['margin'])) {
$margin = $block['style']['spacing']['margin'];
foreach ($margin as $rule => $value) {
if ( str_starts_with( $value, 'var:') ) {
$var_position = strrpos($value, '|');
$variable = substr($value, $var_position + 1 );
$style .= 'margin-' . $rule . ':var(--wp--preset--spacing--' . $variable . '); ';
} else {
$style .= 'margin-' . $rule . ':' . $value . '; ';
}
}
}
return $style;
// echo '<div style="' . $style . '">Block content</div>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment