Retrieving list of Custom Post Types

I’m using the following two strips of code to retrieve a list of categories (1st code) then displaying them in a select menu (2nd code), for my theme options page. I was wondering how I could change this code to do the same, but, retrieve custom post types instead??

Code used to retrieve categories

$tp_categories[0] = array(
'value' => 0,
'label' => ''
);
$tp_cats = get_categories(); $i = 1;
foreach( $tp_cats as $tp_cat ) :
$tp_categories[$tp_cat->cat_ID] = array(
    'value' => $tp_cat->cat_ID,
    'label' => $tp_cat->cat_name
);
$i++;
endforeach;

Code used to display categories in a dropdown select menu

<tr valign="top"><th scope="row"><label for="choose_cat">Choose Category</label></th>
<td>
<select id="choose_cat" name="tp_options[choose_cat]">
<?php
foreach ( $tp_categories as $category ) :
    $label = $category['label'];
    $selected = '';
    if ( $category['value'] == $settings['choose_cat'] )
        $selected = 'selected="selected"';
    echo '<option style="padding-right: 10px;" value="' . esc_attr( $category['value'] ) . '" ' . $selected . '>' . $label . '</option>';
endforeach;
?>
</select>
</td>
</tr>

2 Answers
2

There’s a core function for that: get_post_types():

<?php get_post_types( $args, $output, $operator ); ?>

So, for example, to return public, custom post types by name:

$custom_post_types = get_post_types( array(
    // Set to FALSE to return only custom post types
    '_builtin' => false,
    // Set to TRUE to return only public post types
    'public' => true
) );

Leave a Comment