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.
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.
Share Improve this question edited Nov 30, 2018 at 15:30 fuxia♦ 107k38 gold badges255 silver badges459 bronze badges asked Nov 30, 2018 at 15:25 JakeParisJakeParis 6633 gold badges7 silver badges22 bronze badges1 Answer
Reset to default 14To 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>;
};
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742323999a4422380.html
评论列表(0条)