6

I'd like to get a list (array) of all the post types I registered.

Precisely I would like to retrieve their slugs.

Could someone help me? thanks!

4 Answers 4

11

@EAMann's answer is correct, but there's already a build in WordPress function for fetching all registered post types: get_post_types

<?php
// hook into init late, so everything is registered
// you can also use get_post_types where ever.  Any time after init is usually fine.
add_action( 'init', 'wpse34410_init', 0, 99 );
function wpse34410_init() 
{
    $types = get_post_types( [], 'objects' );
    foreach ( $types as $type ) {
        if ( isset( $type->rewrite->slug ) ) {
            // you'll probably want to do something else.
            echo $type->rewrite->slug;
        }
    }
}
1
  • 4
    TIP: You don't need to call get_post_type_object if you set the get_post_types call to return objects to you, eg. $types = get_post_types( '', 'objects' );
    – t31os
    Commented Nov 23, 2011 at 9:53
3

The easiest way is the following using WordPress function get_post_types();

<?php
$get_cpt_args = array(
    'public'   => true,
    '_builtin' => false
);
$post_types = get_post_types( $get_cpt_args, 'object' ); // use 'names' if you want to get only name of the post type.

// see the registered post types
echo '<pre>';
print_r($post_types);
echo '</pre>';

// do something with array
if ( $post_types ) {
    foreach ( $post_types as $cpt_key => $cpt_val ) {
       // do something.
    }
}
?>
1
2

When you call register_post_type(), it adds your new post type to a global variable called $wp_post_types. So you can get a list of all of your post types from that:

function get_registered_post_types() {
    global $wp_post_types;

    return array_keys( $wp_post_types );
}

The $wp_post_types variable is an array that contains your CPT definitions, with each set of CPT arguments (labels, capabilities, etc) mapped to the slug of the CPT. Calling array_keys() will give you an array of the slugs of your CPTs.

1
  • if you look into wp-includes/post.php the built-in function get_post_types() is returning the same `global $wp_post_types array. why do we create a new function when we already have a built-in function? Commented Nov 3, 2021 at 7:19
-1

A more elegant solution:

<?php
$cpt_args = [
    'public'   => true,
    '_builtin' => false
];

$type_slugs = array_map( function( $type ) {
    return $type->slug;
}, get_post_types( $cpt_args, 'objects' ) );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.