Yus*_*man 1 javascript php wordpress wordpress-gutenberg gutenberg-blocks
如何制作一个下拉列表控件来获取自定义帖子类型的名称?在我的项目中,我想选择一个帖子类型名称并在我的自定义古腾堡块的下拉选择器中获取它!..我该怎么做?
如果为古腾堡块的功能创建下拉列表(选择)edit()
,则可以使用JavaScript 中的getPostTypes()
via 检索注册的帖子类型useSelect()
。一个例子是查询块中用于选择帖子类型的下拉列表。
下面是一个简化的示例,它使用 a<SelectControl/>
显示所有可查看帖子类型的列表,并使选定的帖子类型能够保存块属性。
块.json
{
...
"attributes": {
"postType": {
"type": "string",
"default": "post"
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑.js
import { useSelect } from '@wordpress/data';
import { store as coreStore } from '@wordpress/core-data';
import { SelectControl } from '@wordpress/components';
import { useBlockProps } from '@wordpress/block-editor';
export default function Edit({ attributes, setAttributes }) {
// postType defined in block.json
const { postType } = attributes;
// useSelect to retrieve all post types
const postTypes = useSelect(
(select) => select(coreStore).getPostTypes({ per_page: -1 }), []
);
// Options expects [{label: ..., value: ...}]
var postTypeOptions = !Array.isArray(postTypes) ? postTypes : postTypes
.filter(
// Filter out internal WP post types eg: wp_block, wp_navigation, wp_template, wp_template_part..
postType => postType.viewable == true)
.map(
// Format the options for display in the <SelectControl/>
(postType) => ({
label: postType.labels.singular_name,
value: postType.slug, // the value saved as postType in attributes
})
);
return (
<div {...useBlockProps()}>
<SelectControl
label="Select a Post Type"
value={postType}
options={postTypeOptions}
onChange={(value) => setAttributes({ postType: value })}
/>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
使用 JavaScript 作为编辑器而不是回退到 PHP 的优点是您可以通过使用 Gutenberg 控件(例如<SelectControl/>
.
设置侧边栏可能是放置<SelectControl/>
您的目标的好地方。
归档时间: |
|
查看次数: |
1793 次 |
最近记录: |