Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get reusable block in php

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?

like image 453
protohominid Avatar asked Mar 27 '19 16:03

protohominid


3 Answers

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.

like image 52
protohominid Avatar answered Oct 12 '22 09:10

protohominid


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 );
}

like image 43
Shawn Avatar answered Oct 12 '22 09:10

Shawn


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;
like image 36
red5 Avatar answered Oct 12 '22 07:10

red5