You don’t want to use getCurrentPostId()
from the core/editor
store. This gets the current post ID from the post being edited, not the post in the query loop.
To get that, ensure your block accepts postId
(and possibly postType
) as block context values via the usesContext
key in the block type metadata. This can be added in the block.json
:
{
"$schema": "https://schemas.wp.org/wp/6.6/block.json",
"apiVersion": 3,
"name": "vendor/block-name",
…
"usesContext": [
"postId",
"postType"
]
}
These values will then be available in the context
prop that the edit
component is given:
const Edit = ( { context } ) => {
const blockProps = useBlockProps();
const metaValue = useSelect( ( select ) => {
const { getEntityRecord } = select( 'core' );
if ( ! context.postId ) {
return null;
}
// Get the meta for the post with the current post ID
const post = getEntityRecord( 'postType', context.postType, context.postId );
return post && post.meta ? post.meta['custom_link_text'] : null;
}, [ context.postId, context.postType ] );
Presumably, this is a dynamic block with PHP-generated mark-up. If so, you may wish to consider using the same context
values server-side for consistency:
<?php
// In `render.php` or similar.
$post_id = $block->context['postId'];