You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在WordPress Gutenberg区块中如何用JS编程设置文章属性(如slug/分类)?

Gutenberg区块修改文章属性解决方案

你之前在core/editor中没找到对应接口是因为文章属性的修改能力由@wordpress/core-data包提供,这类操作完全符合Gutenberg的设计规范,修改会自动纳入编辑器全局的撤销/重做栈,不会出现状态冲突。

具体实现步骤

  • 第一步:引入依赖(WordPress脚本自带,无需额外安装)
import { useDispatch, useSelect } from '@wordpress/data';
import { store as coreDataStore } from '@wordpress/core-data';
import { store as editorStore } from '@wordpress/editor';
  • 第二步:获取当前文章基础信息与属性当前值
const { postId, postType, currentCats } = useSelect( ( select ) => {
  return {
    postId: select( editorStore ).getCurrentPostId(),
    postType: select( editorStore ).getCurrentPostType(),
    // 示例:获取默认分类目录的当前选中ID列表
    currentCats: select( editorStore ).getEditedPostAttribute( 'categories' ),
    // 自定义分类法替换为对应slug即可,例:getEditedPostAttribute( 'product_cat' )
  };
}, [] );
  • 第三步:调用接口修改文章属性
const { editEntityRecord } = useDispatch( coreDataStore );
// 示例:给文章添加ID为23的分类项
const addNewCategory = () => {
  // 去重避免重复添加
  const newCats = [ ...new Set( [ ...currentCats, 23 ] ) ];
  editEntityRecord( 'postType', postType, postId, {
    categories: newCats
    // 其他文章属性也可在此处同步修改,例:title: '新文章标题', status: 'pending'
  } );
  // 如需立即保存到数据库可调用以下方法,否则用户点击编辑器全局保存时会自动同步
  // saveEditedEntityRecord( 'postType', postType, postId );
};

注意事项

  • 自定义分类法需要在注册时将show_in_rest参数设为true,否则无法通过REST API修改,操作会被拦截。
  • 无特殊需求不建议主动调用保存接口,跟随全局保存逻辑更符合用户操作预期。

内容的提问来源于stack exchange,提问作者user14487566

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 18:06:03