3

I would like to access the current post ID from within a block. According to this documentation page, it seems like I should be able to get the post ID with:

wp.data.getCurrentPostId();
// or
wp.data.withSelect('core/editor').getCurrentPostId();
// or
wp.editor.getCurrentPostId();

but none of those are correct.

4

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 simply 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 Example extends Component {
    render() {
        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:

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

class Example 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()
    };
})(Example);

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.