[solved] PHP Block: How to get the post ID inside a custom block if in edit mode?

I need to get the post ID in a Custom PHP Block while working in the editor.

This is not working:

global $post;
echo $post->ID;

Nor is this:

echo get_queried_object_id();

Also this does not work:

if(isset($_GET['action']) && $_GET['action'] === 'edit') {
    $post_id = $_GET['post'];
}

This is not working eihter:

get_current_screen()->is_block_editor()

Can this be that hard?

This works - but it is not elegant. There must be a better way.

global $post;

if(!isset($post->ID)) {
    parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $queries);
    $post_id = $queries['post'];
}

@MichelyWeb try using the “Load edited post” option of the Block action. For dynamic posts, it loads the current post into the $post variable during the editing.

2 Likes