How do I get the current post ID within a Gutenberg/Block Editor block?

To simply get the value you can call the selector:

const post_id = wp.data.select("core/editor").getCurrentPostId();

In this case, the post id won’t change, so you could assign the value to a constant outside of the component:

const { Component } = wp.element;
const { getCurrentPostId } = wp.data.select("core/editor");
const post_id = getCurrentPostId();

// class component
class ExampleClassComp extends Component {
    render() {
        return <div>{post_id}</div>;
    }
}

// functional component
const ExampleFunctionalComp = () => {
    return <div>{post_id}</div>;
};

But if the value changes then it is better to connect the component to the store (for example if using getGlobalBlockCount()). So every time the value updates the selector will re-render the component. Here is an example:

Class Component:

const { Component } = wp.element;
const { withSelect } = wp.data;

class ExampleClassComp extends Component {
    render() {
        const { post_id, block_count } = this.props;

        return <div>{block_count}</div>;
    }
}

export default withSelect(select => {
    const { getCurrentPostId, getGlobalBlockCount } = select("core/editor");

    return {
        post_id: getCurrentPostId(),
        block_count: getGlobalBlockCount()
    };
})(ExampleClassComp);

Functional Component:

const { useSelect } = wp.data;

export const ExampleFunctionalComp = () => {
    const post_id = useSelect(select =>
        select("core/editor").getCurrentPostId()
    );

    const block_count = useSelect(select =>
        select("core/editor").getGlobalBlockCount()
    );

    return <div>{block_count}</div>;
};

Leave a Comment