我已经非常广泛地使用了自定义块选项。我为自定义帖子类型启用编辑器,但使用自定义模板template_lock
设置为true
:
\'template\' => array(
array(\'pb/custom-block-name\'),
),
\'template_lock\' => true
然后我使用
allowed_block_types_all
筛选以仅允许post类型的自定义块:
function pb_allowed_block_types($allowed_block_types, $block_editor_context) {
if (!$block_editor_context->post || $block_editor_context->post->post_type !== \'custom_post_type\') {
return $allowed_block_types;
}
return array(
\'pb/custom-block-name\',
);
}
add_filter(\'allowed_block_types_all\', \'pb_allowed_block_types\', 10, 2);
最后,我使用
useEntityProp
要获取和设置元,请执行以下操作:
import { __ } from \'@wordpress/i18n\';
import { useSelect } from \'@wordpress/data\';
import { useEntityProp } from \'@wordpress/core-data\';
const Edit = (props) => {
const postType = useSelect((select) => (
select(\'core/editor\').getCurrentPostType()
));
const [meta, setMeta] = useEntityProp(\'postType\', postType, \'meta\');
return (
<TextControl
label={ __(\'Label\', \'pb\') }
value={ meta._pb_meta_slug }
onChange={ (value) => setMeta({_pb_meta_slug: value}) }
/>
);
};
确保您使用
register_post_meta
要为自定义帖子类型注册所有帖子元,否则将无法保存:
register_post_meta(\'custom_post_type\', \'_pb_meta_slug\', array(
\'type\' => \'string\',
\'single\' => true,
\'auth_callback\' => function() {
return current_user_can(\'edit_posts\');
},
\'show_in_rest\' => true,
));