spot_img
HomeWordPress教程wordpress建站公司 如何在 Gutenberg/Block Editor 块中获取当前的帖子 ID?

wordpress建站公司 如何在 Gutenberg/Block Editor 块中获取当前的帖子 ID?

spot_img

JasperAI 10000字免费额度试用

我想从一个块中访问当前的帖子 ID。 根据此文档页面,似乎我应该能够通过以下方式获取帖子 ID:

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

但这些都不正确。

WordPress divi主题

要简单地获取值,您可以调用选择器:

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

在这种情况下,帖子 ID 不会更改,因此您可以将该值分配给组件外部的常量:

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>;
};

但是如果值发生变化,那么最好将组件连接到商店(例如,如果使用 getGlobalBlockCount()). 所以每次值更新时,选择器都会重新渲染组件。 这是一个例子:

类组件:

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);

功能组件:

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>;
};

5分钟生成10篇英文软文article forge软件试用
siteground guangda
WordPress花园官方账号
WordPress花园隶致力于为广大跨境电商和独立站爱好者提供优质的WordPress教程、Woocommerce教程、Facebook、Twitter、tiktok、Instagram教程和谷歌SEO教程等资料和对应的建站推广服务。关注‘哟派出海’公众号了解最新资讯。粉丝福利:Shopline免费独立站建设14天优惠 商务合作: [email protected]
RELATED ARTICLES