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.

  • 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 '21 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 '21 at 15:57

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 ] );
  • 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 '21 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 '21 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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