For the life of me, I can't find anything on how to do this: simply output a reusable gutenberg block via php in a theme template. Seems like it should be doable. Anyone?
Possibly answering my own question. Please tell me if there's a better/easier way to do this.
<?php
// get reusable gutenberg block:
$gblock = get_post( 7418 );
echo apply_filters( 'the_content', $gblock->post_content );
?>
The first downside I can see to this is that it's inconvenient to have to hunt down the post ID of the block.
I just found this handy little snippet. It adds the Reusable blocks as an admin link. Once there you can easily determine the ID of the reusable block that you need. https://github.com/WordPress/gutenberg/issues/15549
add_menu_page( 'linked_url', 'Reusable Blocks', 'read', 'edit.php?post_type=wp_block', '', 'dashicons-editor-table', 22 );
}
As pointed out by gtamborero here, you can use get_page_by_title(), but you need to specify that this is a 'wp_block'. His example works for me (using WP 5.8.1):
get_page_by_title( 'Your Title', OBJECT, 'wp_block' );
I'm using it like this:
$myPost = get_page_by_title( 'Your Title', OBJECT, 'wp_block' );
$myContent = apply_filters('the_content', $myPost->post_content);
echo $myContent;
Combining several answers into an approach with WP_Query, this is a function that can be reused all over the place. Place it in functions.php and call it from templates with get_reusable_block('block-title');
.
function get_reusable_block($block) {
// important to have post_type as 'wp_block' since it is a reusable block
$query = new WP_Query(
array(
'post_type' => 'wp_block',
'title' => $block,
'post_status' => 'published',
'posts_per_page' => 1,
)
);
if (!empty($query->post)) {
$reusable_block = $query->post;
$reusable_block_content = apply_filters('the_content', $reusable_block->post_content);
return $reusable_block_content;
} else {
return '';
}
}
There is a way to query by title without using get_page_by_title (depreciated in 6.2). We can use wp_query() with the wp_blocks post type where reusable blocks are stored.
In the example here, it asks for a wp_block that is titled "Global Call To Action" and published.
$query = new WP_Query(
array(
'post_type' => 'wp_block',
'title' => 'Global Call To Action',
'post_status' => 'publish',
'posts_per_page' => 1
)
);
if ( $query->have_posts() ) {
$object = $query->post;
echo apply_filters('the_content', $object->post_content);
}
wp_reset_postdata();
© 2022 - 2024 — McMap. All rights reserved.