While working with the block themes and block patterns, we can access post data or metadata through given methods.
- By using
render_callback
inregister_block_pattern
register_block_pattern(
'your-theme/custom-pattern',
array(
'title' => 'Custom Pattern',
'content' => '<!-- wp:paragraph {"placeholder":"Write something..."} /-->',
'categories' => array( 'text' ),
'render_callback' => function() {
$post_id = get_the_ID(); // Here we have access to post ID
$post_title = get_the_title( $post_id ); // Here we have access to post title
// Here is the Output custom HTML or content.
echo '<h2>' . esc_html( $post_title ) . '</h2>';
echo '<div>' . esc_html( get_post_meta( $post_id , 'custom_field' , true ) ) . '</div>';
},
)
);
- By Using
render_template_part
register_block_pattern(
'your-theme/custom-pattern',
array(
'title' => 'Custom Pattern',
'content' => '<!-- wp:paragraph {"placeholder":"Write something..."} /-->',
'categories' => array( 'text' ),
'render_template_part' => 'template-parts/block-pattern.php', // Path to your PHP template file
)
);
In this case we can access post data inside template-parts/block-pattern.php
<?php
$post_id = get_the_ID(); // Access to the post ID.
$post_title = get_the_title($post_id); // Access to the post title.
?>
<div>
<h2><?php echo esc_html( $post_title ); ?></h2>
<div><?php echo esc_html( get_post_meta( $post_id, 'custom_field', true ) ); ?></div>
</div>
Please let me know if this helps.