Get list of all registered post types slugs

The question:

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!

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

@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;
        }
    }
}

Method 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.

Method 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.
    }
}
?>

Method 4

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' ) );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment