7

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.

1 Answer 1

14

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>;
};
1
  • In my case, wp.data.select("core/editor") is undefined. Commented Feb 12 at 16:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.