Support

Account

Home Forums Gutenberg How to get current post ID in block template on edit screen?

Solved

How to get current post ID in block template on edit screen?

  • Hello,

    working with Gutenberg 4.3.0 and ACF Pro 5.8.0-beta2, I use a callback function to include a block template in PHP like in the example: https://www.advancedcustomfields.com/blog/acf-5-8-introducing-acf-blocks-for-gutenberg/

    I need to access the post ID in that template. It seems obvious:
    global $post
    and go on.

    But… It works only on the front-end; $post returns NULL at the admin side in block preview and edit window. I also tried $_GET[‘post’] to grab the ID but without success.

    Am I missing something?

    PS: Additionally I’d be happy to access the same ID (on edit screen) in filters like ‘acf/load_value’ or ‘acf/load_field’ but I can’t…

  • Digging through code, it appears that Gutenberg blocks are just custom post type. What’s happening is that block (and so their previews) are standalone: $post_id is actually the block ID! On the frontend, blocks are rendered inside a post, but it’s not always the case. So the problem is a little trickier than I first thought…

    I found a temporary workaround though: add this (second line) in /wp-content/plugins/advanced-custom-fields-pro/includes/gutenberg/blocks.php line 403:

    `
    // render_callback vars
    $content = ”;
    $is_preview = true;
    $block[‘data’][‘post_id’] = acf_maybe_get_POST(‘post_id’);
    `

    Next edit your custom block template, add this at the top:

    `
    if(!$GLOBALS[‘post’] && $block[‘data’][‘post_id’]) {
    setup_postdata($GLOBALS[‘post’] =& get_post($block[‘data’][‘post_id’]));
    }
    `

    And don’t forget to add this too at the end:

    `
    wp_reset_postdata()
    `

    Now you can access current parent post datas. Functions like the_title() work too.

    Hope it helps, and hope ACF team will find a cleaner way to add this feature 🙂

  • Hi, thanks for pointing to acf_maybe_get_POST()! As I don’t want to edit core files, I wrote a helper which works for me so far within the block template:

    function my_acf_post_id() {
    	if ( is_admin() && function_exists( 'acf_maybe_get_POST' ) ) :
    		return intval( acf_maybe_get_POST( 'post_id' ) );
    	else :
    		global $post;
    		return $post->ID;
    	endif;
    }

    Definitely, I agree that a block instance should contain the post ID or it should be accessible in another elegant way.

  • Good call, didn’t think we could use acf_maybe_get_POST('post_id') on the frontend! Much cleaner, thanks.

  • It seems that we’ve got it as a parameter in beta3!

    function render_callback( $block, $content = '', $is_preview = false, $post_id = 0 ) {...}

Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.