How to Create a Gutenberg Block with Advanced Custom Fields (ACF)

https://app.gitbook.com/@wordpress-lionel/s/wordpress-advand/how-to-create-a-gutenberg-block-with-advanced-custom-fields-acf

wp-content/themes/twentytwentyone/functions.php

function acf_portfolio_item_block() {
  // check function exists
  if( function_exists('acf_register_block') ) {
    // register a portfolio item block
    acf_register_block(array(
      'name'				=> 'portfolio-item',
      'title'				=> __('Portfolio Item'),
      'description'		=> __('A custom block for portfolio items.'),
      'render_template'	=> 'template-parts/blocks/portfolio-item/block-portfolio-item.php',
      'category'			=> 'layout',
      'icon'				=> 'excerpt-view',
      'keywords'			=> array( 'portfolio' ),
    ));
  }
}
add_action('acf/init', 'acf_portfolio_item_block');

wp-content/themes/twentytwentyone/template-parts/blocks/portfolio-item/block-portfolio-item.php

<?php
$logo = get_field( 'logo' );
$title = get_field( 'title' );
$description = get_field( 'description' );
echo '<div class="portfolio-item">';
if( !empty( $logo ) )
  echo wp_get_attachment_image( $logo['ID'], 'thumbnail', null, array( 'class' => 'portfolio-logo alignleft' ) );
if( !empty( $title ) )
  echo '<h3 class="portfolio-title">' . $title . '</h3>';
if( !empty( $description ) )
  echo '<div class="portfolio-description">' . $description . '</div>';
echo '</div>';
?>

Last updated