Home Forums Gutenberg Include ACF Block from code Reply To: Include ACF Block from code

  • I’ve achieved this by hooking into the function that ACF uses to render blocks, which enqueues the correct JS/CSS and template you specified when you declared the block.

    You then need to manually pass in attributes that will be used in your template in place of the block’s custom fields (as these won’t be available, obviously!)

    // functions.php
     * Render an ACF block with your chosen attrs in place
     * Allows you to use the block within PHP templates
     * Note: Block template may need to be adjusted to read this data
    function launchpad_render_acf_block( $block_name, $attrs = [] ) {
    	$block = acf_get_block_type( $block_name );
    	$content = '';
    	$is_preview = false;
    	foreach( $attrs as $attr => $val) {
    		$block['data'][$attr] = $val;
    	echo acf_rendered_block( $block, $content, $is_preview );

    Call the function in your template file and pass it an array of attributes:

    // archive.php
    launchpad_render_acf_block('acf/post-grid', ['block_post_grid_posts' => $grid_posts]);

    I’ve specifically placed the attributes in the same place that ACF stores custom field data within a block, but this doesn’t live update in admin so in your block template you should first look for the custom field data, followed by the $block['data'] eg:

    // block-template.php
    if( get_field('block_post_grid_posts') ) {
      $grid_posts = get_field('block_post_grid_posts');
    } elseif ( $block['data'] && $block['data']['block_post_grid_posts'] ) {
      $grid_posts = $block['data']['block_post_grid_posts'];