如何在WordPress Gutenberg侧边栏插件中修改文章标签与分类
你之前的代码不生效主要是editEntityRecord参数匹配错误,且没有正确合并现有分类/标签数据导致覆盖,以下是可直接落地的实现方案:
1 补全withSelect数据获取逻辑
首先需要在withSelect中拿到当前编辑文章的ID、已绑定的分类ID数组、已绑定的标签ID数组,避免新增时覆盖原有数据:
export default compose([ withSelect(select => { // 获取当前编辑文章基础信息 const currentPost = select('core/editor').getCurrentPost(); // 获取已选中的分类、标签ID数组,默认空数组避免取值报错 const existingCategories = select('core/editor').getEditedPostAttribute('categories') || []; const existingTags = select('core/editor').getEditedPostAttribute('tags') || []; return { currentPostId: currentPost.id, existingCategories, existingTags } }), // withDispatch逻辑见下方 ])
2 实现分类/标签增删逻辑
针对不同场景的操作,withDispatch的实现如下:
2.1 已有分类/标签添加(站点中已存在该分类/标签,直接绑定到文章)
withDispatch((dispatch, ownProps) => { // 直接调用Gutenberg提供的editPost方法操作当前文章,比editEntityRecord更便捷 const { editPost } = dispatch('core/editor'); return { onTaxonomiesAdd: (categoryId, tagId) => { // 合并新老ID并去重 const updatedCategories = [...new Set([...ownProps.existingCategories, categoryId])]; const updatedTags = [...new Set([...ownProps.existingTags, tagId])]; // 更新文章属性 editPost({ categories: updatedCategories, tags: updatedTags }); }, // 可选:移除指定分类/标签 onTaxonomiesRemove: (categoryId = null, tagId = null) => { let updatedCategories = ownProps.existingCategories; let updatedTags = ownProps.existingTags; if(categoryId) updatedCategories = updatedCategories.filter(id => id !== categoryId); if(tagId) updatedTags = updatedTags.filter(id => id !== tagId); editPost({ categories: updatedCategories, tags: updatedTags }); } } })
2.2 新增未存在的分类/标签后绑定到文章
如果需要先在站点中创建全新的分类/标签,再绑定到当前文章,使用以下逻辑:
withDispatch((dispatch, ownProps) => { const { editPost } = dispatch('core/editor'); const { createEntityRecord } = dispatch('core'); return { // 示例:新建标签并绑定到文章 createAndAddTag: (tagName, tagSlug = '') => { createEntityRecord('taxonomy', 'post_tag', { name: tagName, slug: tagSlug }).then(newTag => { // 拿到新创建的标签ID后追加到文章 const updatedTags = [...new Set([...ownProps.existingTags, newTag.id])]; editPost({ tags: updatedTags }); }) }, // 新建分类同理,把taxonomy参数改为'category'即可 createAndAddCategory: (catName, catSlug = '') => { createEntityRecord('taxonomy', 'category', { name: catName, slug: catSlug }).then(newCat => { const updatedCats = [...new Set([...ownProps.existingCategories, newCat.id])]; editPost({ categories: updatedCats }); }) } } })
3 常见问题排查
- 确保插件注册脚本时已声明
wp-editor、wp-data、wp-components为依赖,避免核心变量未定义报错 - 分类、标签字段存储的是term ID数组,传名称、slug等格式数据会不生效
- 如果操作的是自定义分类法,注册时必须设置
show_in_rest => true,否则Gutenberg无法通过REST接口读写该分类法数据
内容的提问来源于stack exchange,提问作者Matt Woodward
相关产品推荐
相关产品推荐

