首先,注册元字段,这样您就可以在其中保存值。这会出现在您的插件文件或functions.php
中。
register_post_meta('post','customname_meta_subtitle',array(
'show_in_rest' => true,'type' => 'string','single' => true
));
register_post_meta('post','customname_meta_header_height','single' => true
));
您可以检查documentation。我们告诉WordPress创建2个新的帖子元字段,分别使用键customname_meta_subtitle
和customname_meta_header_height
,将在古腾堡部分中使用它们。
对于ES代码,您将需要以下内容:
const { registerPlugin } = wp.plugins
const { PluginDocumentSettingPanel } = wp.editPost
const { RadioControl,TextControl } = wp.components
const { withState } = wp.compose
const { withSelect,withDispatch } = wp.data
let SubtitleControl = ({ subtitle,handleSubtitleChange }) => (
<TextControl
label="Set subtitle"
value={subtitle}
onChange={subtitle => handleSubtitleChange(subtitle)}
/>
);
SubtitleControl = withSelect(
(select) => {
return {
subtitle: select('core/editor').getEditedPostAttribute('meta')['customname_meta_subtitle']
}
}
)(SubtitleControl);
SubtitleControl = withDispatch(
(dispatch) => {
return {
handleSubtitleChange: (value) => {
dispatch('core/editor').editPost({ meta: { customname_meta_subtitle: value } })
}
}
}
)(SubtitleControl);
let HeaderImageHeightControl = ({ height,handleHeightChange }) => (
<RadioControl
label="Set image height"
help="Set the height of the header image"
selected={height}
options={[
{ label: '100',value: '1' },{ label: '200',value: '2' },]}
onChange={handleHeightChange}
/>
);
HeaderImageHeightControl = withSelect(
(select) => {
return {
height: select('core/editor').getEditedPostAttribute('meta')['customname_meta_header_height']
}
}
)(HeaderImageHeightControl);
HeaderImageHeightControl = withDispatch(
(dispatch) => {
return {
handleHeightChange: value => {
dispatch('core/editor').editPost({ meta: { customname_meta_header_height: value } })
}
}
}
)(HeaderImageHeightControl);
const PluginDocumentSettingPanelDemo = () => (
<PluginDocumentSettingPanel
name="custom-panel"
title="Custom Panel"
className="custom-panel"
>
<SubtitleControl />
<HeaderImageHeightControl />
</PluginDocumentSettingPanel>
)
registerPlugin('plugin-document-setting-panel-demo',{
render: PluginDocumentSettingPanelDemo
})
official WP tutorial中描述了大部分代码,但是请随时询问是否不清楚。
最后,要使用新值,您可以执行以下操作:
<h1><?php echo get_post_meta(get_the_ID(),'customname_meta_subtitle')[0]; ?></h1>
<h1><?php echo get_post_meta(get_the_ID(),'customname_meta_header_height')[0]; ?></h1>
这将在发布模板文件中使用,以实现元字段信息的前端可视化。
我希望这会有所帮助!
本文链接:https://www.f2er.com/3085285.html