'How can I make a dropdown list control that fetches names of custom posts types?
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?
Solution 1:[1]
$post_types = get_post_types( [
'public' => true,
'_builtin' => false,
], 'objects', 'and' );
<select name="post-types" class="form-control">
<?php
foreach ( $post_types as $post_type ) {
?>
<option value="<?php echo esc_attr($post_type->name); ?>">
<?php echo esc_html($post_type->label) ?>
</option>
<?php
}
?>
</select>
If you want to pass variables ( in this example : CPT ) to block scripts , you can use wp_localize_scripts :
wp_enqueue_script('gutenberg-select-cpt-block', $pathToScript, [], null,
true);
wp_localize_script(
'gutenberg-select-cpt-block',
YOURJSOBJECT,
['post_types' => $post_types] <--- array of data you want to pass
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
