【问题标题】:In a WordPress Gutenberg block how to set Post attributes (e.g. slug/category) programmatically in JavaScript?在 WordPress Gutenberg 块中,如何在 JavaScript 中以编程方式设置 Post 属性(例如 slug/category)?
【发布时间】:2021-09-23 06:46:15
【问题描述】:

我有一个块可以将用户输入保存到自定义元字段 - 在古腾堡。我还希望能够在我的块中以编程方式为包含该块的 Post 设置 Post 属性。 (在 JS 中)。例如;我希望能够通过块中的代码将术语(类别或自定义分类)添加到帖子中。

我明白这意味着一个块正在编辑帖子内容,我不确定这是模型的一部分吗? (虽然您可以编辑帖子元数据)。

我查看了核心/编辑器中的方法,但没有看到任何关于设置值的内容。

谢谢

【问题讨论】:

    标签: wordpress custom-taxonomy wordpress-gutenberg


    【解决方案1】:

    您可以使用useDispatch() 钩子和editEntityRecord() 函数来修改edit 函数中的帖子属性。

    首先,导入它:

    import { useDispatch, useSelect } from '@wordpress/data';
    

    然后在 edit 函数中设置您需要的部分:

    const { editEntityRecord } = useDispatch('core');
    
    const {
        postType,
        postId,
    } = useSelect((select) => {
        const {
            getCurrentPostType,
            getCurrentPostId,
        } = select('core/editor');
    
        return {
            postType: getCurrentPostType(),
            postId: getCurrentPostId(),
        };
    }, []);
    

    然后,无论您想在哪里更改属性(例如 onChange):

    editEntityRecord('postType', postType, postId, {
        slug: 'your-new-slug',
    });
    

    【讨论】:

      猜你喜欢
      • 2020-07-15
      • 1970-01-01
      • 2011-03-15
      • 1970-01-01
      • 2023-03-31
      • 2021-06-22
      • 2023-01-03
      • 2019-05-09
      • 2011-01-02
      相关资源
      最近更新 更多