Support

Account

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

  • 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 🙂