admin管理员组

文章数量:1122832

How should I be able to query things like specific metadata or any other thing from the post object? Apparently I don't have access to basic functions like get_the_ID() or similar functions inside block theme patterns (where I at least can use php).

How should I be able to query things like specific metadata or any other thing from the post object? Apparently I don't have access to basic functions like get_the_ID() or similar functions inside block theme patterns (where I at least can use php).

Share Improve this question asked Feb 14, 2024 at 15:27 thebigJthebigJ 11 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

While working with the block themes and block patterns, we can access post data or metadata through given methods.

  1. By using render_callback in register_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>';
        }, 
    )
);
  1. 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.

本文标签: How do I access the current post object within a block theme template or pattern