How can I make a dropdown list control that fetches names of custom posts types? In my project I want to select a post type name and fetch it in drop down selector in my custom Gutenberg Block!.. How can I do this?
How can I make a dropdown list control that fetches names of custom posts types? In my project I want to select a post type name and fetch it in drop down selector in my custom Gutenberg Block!.. How can I do this?
2
Answers
If you want to pass variables ( in this example : CPT ) to block scripts , you can use wp_localize_scripts :
If creating a dropdown list (select) for the
edit()
function of a Gutenberg block, registered post types can be retrieved withgetPostTypes()
viauseSelect()
in JavaScript. An example of this is the dropdown in the Query Block to select a Post Type.Below is a simplified example that uses a
<SelectControl/>
to display a list of all viewable post types, and enables a selected postType to be saved the blocks attributes.block.json
edit.js
The advantage of using JavaScript for the Editor instead of falling back to PHP is you can keep the UI consistent by using Gutenberg controls like
<SelectControl/>
.The Settings Sidebar may be a good place to put your
<SelectControl/>
depending on your goal.