开发Gutenberg插件块:添加时自动选中自定义分类
Gutenberg块自动选中自定义分类的实现方案
我正在开发一款Gutenberg插件块,需求是:当该块添加到文章时,自动选中插件初始化阶段通过PHP的wp_insert_term创建的自定义分类。
核心问题:设置选中分类需要传入分类ID,但仅已知该分类的名称与slug,尝试通过core和core/editor获取分类元信息未果,最终通过apiFetch实现了需求。
尝试的初始代码
// 尝试获取分类元信息,但不知道如何使用 const allCategories = select('core').getTaxonomy('category'); // 获取当前已选中的分类ID列表 const categories = select( 'core/editor' ).getEditedPostAttribute( 'categories' ); if(!(allCategories && categories)){ return; } // 参考资料中的代码逻辑,仅修改了dispatch部分 if(! categories.includes(CATEGORY_NAME)){ const newCategories = [...categories, CATEGORY_NAME]; // 这里需要传入分类ID而非名称,暂时硬编码ID为5 dispatch( 'core/editor' ).editPost( { 'categories': [5] } ); const is_category_panel_open = select( 'core/editor' ).isEditorPanelOpened( 'taxonomy-panel-category' ); if ( is_category_panel_open ) { // 关闭再重新打开分类面板以刷新UI dispatch( 'core/editor' ).toggleEditorPanelOpened( 'taxonomy-panel-category' ); dispatch( 'core/editor' ).toggleEditorPanelOpened( 'taxonomy-panel-category' ); } }
注:
select、dispatch来自WordPress官方包,目标分类在PHP的init动作中通过wp_insert_term创建。
最终API Fetch实现方案
import {CATEGORY_SLUG} from '../../consts'; import {select, dispatch} from '@wordpress/data'; import apiFetch from '@wordpress/api-fetch'; export function ensureCategorySelected(){ const categoriesSelected = select( 'core/editor' ).getEditedPostAttribute( 'categories' ); if(!categoriesSelected) return; ensure(categoriesSelected); } /** * @param {Array} categoriesSelected 当前已选中的分类ID数组 */ async function ensure(categoriesSelected){ let id = 0; // 通过WP REST API获取所有分类列表 const categories = await apiFetch({ path: `/wp/v2/categories`, method: 'GET', }); if(!categories){ return; } // 遍历分类列表,通过slug匹配目标分类ID for(const category of categories){ if(category.slug === CATEGORY_SLUG){ id = category.id; break; } } if(id === 0){ return; } // 构造新的选中分类数组(避免直接修改原数组) const newCategories = [...categoriesSelected, id]; // 更新文章的选中分类 dispatch( 'core/editor' ).editPost( { 'categories': newCategories } ); // 获取分类面板的展开状态 const is_category_panel_open = select( 'core/editor' ).isEditorPanelOpened( 'taxonomy-panel-category' ); // 如果分类面板处于展开状态,刷新面板UI if ( is_category_panel_open ) { dispatch( 'core/editor' ).toggleEditorPanelOpened( 'taxonomy-panel-category' ); dispatch( 'core/editor' ).toggleEditorPanelOpened( 'taxonomy-panel-category' ); } }
内容的提问来源于stack exchange,提问作者Egor Demeshko
相关产品推荐
相关产品推荐

