Skip to content

Instantly share code, notes, and snippets.

@joseph-farruggio
Last active November 14, 2023 23:07
Show Gist options
  • Save joseph-farruggio/2c4e7e427625c69783da6fc461969a9a to your computer and use it in GitHub Desktop.
Save joseph-farruggio/2c4e7e427625c69783da6fc461969a9a to your computer and use it in GitHub Desktop.
<?php
/**
* A function that takes an array of HTML attribute
* key/value pairs and returns a string of HTML attributes.
**/
function unwrap_html_attrs($attrs)
{
$attributes = '';
foreach ($attrs as $key => $value) {
$attributes .= sprintf(' %s="%s"', $key, esc_attr($value));
}
return $attributes;
}
/**
* A wrapper for the get_block_wrapper_attributes() function
* that allows us to pass in an array of HTML attribute key/value pairs.
* get_block_wrapper_attributes() is only returned on the front-end while
* the attributes that we set ourselves are returned in the block editor.
**/
function acf_block_attributes_wrapper($block, $is_preview = false, $attrs = [])
{
$attrs['id'] = isset($attrs['id']) ?: $block['id'];
$attrs['class'] = isset($attrs['class']) ? $attrs['class'] . ' ' . $block['className'] : $block['className'];
// Get the text alignment class name (alignwide or alignfull)
if (!empty($block['alignText'])) {
$attrs['class'] .= ' has-text-align-' . $block['alignText'];
}
// To do: Check for other block styles that are missed in get_block_wrapper_attributes()
if ($is_preview) {
return unwrap_html_attrs($attrs);
} else {
return get_block_wrapper_attributes($attrs);
}
}
@joseph-farruggio
Copy link
Author

joseph-farruggio commented Sep 20, 2023

Why this code was written:
get_block_wrapper_attributes() is a helpful function for getting a string of attributes for the wrapper div of your ACF block. The problem is, not all block attributes are accessible to get_block_wrapper_attributes(). Mainly, attributes that are added by ACF and are not a part of Core.

Example usage

<?php
// In my block's render template:
$class_name = "hero-block";

$block_wrapper_attrs = acf_block_attributes_wrapper($block, $is_preview, ['class' => $class_name]);
?>

<div <?= $block_wrapper_attrs; ?>>
 This is my block
</div>

@kingkool68
Copy link

On line 12 you should run $value through esc_attr()

@joseph-farruggio
Copy link
Author

On line 12 you should run $value through esc_attr()

Good call

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment