0

I am trying to get the current post ID in the render_callback function to generate related posts. However, the global $post object gives null.

I use this code for example from here:

add_action( 'init', function() {
    register_block_type('fc/related-posts', array(
        'render_callback' => function() {
            global $post;
            var_dump($post); // null
        }
    ));
});

It will be fired on init but just $wp object works others like $wp_query or $post are null.

2
  • The actual render_callback won't be called until the template is being rendered though will it? Can you get a stack trace to work out exactly when it is being called?
    – Rup
    Jul 4, 2021 at 15:47
  • And it really shouldn't matter but I'd try var_dump( get_post() ); too, just to make sure there isn't some odd globals scoping problem with lambdas.
    – Rup
    Jul 4, 2021 at 15:57

2 Answers 2

1

When you declare your block, you need to tell WP that it needs context, either by using usesContext in JS/JSON or uses_context in PHP.

E.g in PHP:

        'render_callback' => 'render_my_block',
        'uses_context' => [ 'postId' ],

This value then takes an array of context identifiers, e.g. postId which can then be grabbed in the edit component for rendering, or in PHP at runtime:

function render_my_block( array $attributes, string $content, $block ) : string {
    $post_id = $block->context['postId'];

If you do not declare that your block requires the post ID then $block->context['postId'] will have no value.

-1

I recently had the same issue. The workaround I used was to save the current post id as an attribute of the block:

const currentPostId = useSelect( ( select ) => {
    return select( 'core/editor' ).getCurrentPostId();
}, [] );

useEffect( () => {
    if ( currentPostId && currentPostId !== postId ) {
        setAttributes( { postId: currentPostId } );
    }
}, [ currentPostId ] );
3
  • Thanks Phil, it will work but for me .getCurrentPostId() gives null as well. I could not understand what the problem is!
    – Amir 2mi
    Jul 8, 2021 at 12:10
  • Well that is weird. I believe getCurrentPostId() is an async function, so you need to make sure you are wrapping it with useSelect (or perviously a withSelect HOC) in your JS so that you are "subscribing" to any updates of the post ID.
    – Phil
    Jul 8, 2021 at 13:12
  • this won't work, especially if the block is inside a loop type block such as the query block, or in a template. There is no way to know the final post ID from the block editor, it has to be done in PHP when the block is rendered
    – Tom J Nowell
    Nov 21, 2022 at 15:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.