Skip to content

Instantly share code, notes, and snippets.

@tessak22
Created March 12, 2019 12:06
Show Gist options
  • Save tessak22/a81398621b32c23358cae5f3a1d31379 to your computer and use it in GitHub Desktop.
Save tessak22/a81398621b32c23358cae5f3a1d31379 to your computer and use it in GitHub Desktop.
Hero Gutenberg Block using Advanced Custom Fields 5.8 Pro
/**
* Register hero block
*/
add_action('acf/init', 'hero');
function hero() {
// check function exists
if( function_exists('acf_register_block') ) {
// register a hero block
acf_register_block(array(
'name' => 'hero',
'title' => __('Hero'),
'description' => __('Image background with text & call to action.'),
'render_callback' => 'hero_render_callback',
'category' => 'formatting',
'icon' => 'format-image',
'mode' => 'preview',
'keywords' => array( 'hero', 'image' ),
));
}
}
/**
* This is the callback that displays the hero block
*
* @param array $block The block settings and attributes.
* @param string $content The block content (emtpy string).
* @param bool $is_preview True during AJAX preview.
*/
function hero_render_callback( $block, $content = '', $is_preview = false ) {
// create id attribute for specific styling
$id = 'hero-' . $block['id'];
// create align class ("alignwide") from block setting ("wide")
$align_class = $block['align'] ? 'align' . $block['align'] : '';
// ACF field variables
$image = get_field('image');
$headline = get_field('headline');
$paragraph = get_field('paragraph');
$cta = get_field('cta');
?>
<section id="<?php echo $id; ?>" class="hero <?php echo $align_class; ?>" style="background-image: url(<?php echo $image; ?>);">
<?php if ( $headline ): ?>
<h2><?php echo $headline; ?></h2>
<?php endif; ?>
<?php if ( $paragraph ): ?>
<p><?php echo $paragraph; ?></p>
<?php endif; ?>
<?php if ( $cta ): ?>
<a class="button" href="<?php echo $cta['url']; ?>" target="<?php echo $cta['target']; ?>"><?php echo $cta['title']; ?></a>
<?php endif; ?>
</section>
<?php
}
.hero {
background-attachment: fixed;
background-repeat: no-repeat;
background-size: cover;
background-position: top center;
padding: 100px 0;
color: #fff;
text-align: center;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment