Skip to content

Instantly share code, notes, and snippets.

@pramodjodhani
Last active December 15, 2022 11:17
Show Gist options
  • Save pramodjodhani/b701001fc7fb3aac78d6c37ca4ced407 to your computer and use it in GitHub Desktop.
Save pramodjodhani/b701001fc7fb3aac78d6c37ca4ced407 to your computer and use it in GitHub Desktop.
<?php
/**
* Display a dropdown of non-hierarchical post types.
* For hierarchical CPTs you can use `wp_dropdown_pages`.
*
* @param string $args Arguments.
*
* @return void
*/
public function dropdown_non_hierarchical_posts( $args ) {
$defaults = array(
'show_option_none' => '',
'name' => '',
'selected' => '',
'post_type' => '',
);
$args = wp_parse_args( $args, $defaults );
if ( empty( $args['post_type'] ) ) {
return;
}
$post_items = get_posts(
array(
'post_type' => $args['post_type'],
'post_status' => 'publish',
'suppress_filters' => false,
'posts_per_page' => -1,
)
);
if ( empty( $post_items ) ) {
return;
}
?>
<select name="<?php echo esc_attr( $args['name'] ); ?>" id="<?php echo esc_attr( $args['name'] ); ?>">
<option value="0"><?php echo esc_html( $args['show_option_none'] ); ?></option>
<?php
foreach ( $post_items as $_post ) {
$selected = intval( $args['selected'] ) === $_post->ID ? ' selected=' : '';
echo sprintf( '<option value="%d" %s>%s</optio>', esc_attr( $_post->ID ), esc_attr( $selected ), esc_html( $_post->post_title ) );
}
?>
</select>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment