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!
@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;
}
}
}
get_post_type_object
if you set the get_post_types
call to return objects to you, eg. $types = get_post_types( '', 'objects' );
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.
}
}
?>
'object'
in $post_types = get_post_types( $get_cpt_args, 'object' )
should be corrected to be plural 'objects'
: $post_types = get_post_types( $get_cpt_args, 'objects' )
ref: developer.wordpress.org/reference/functions/get_post_types
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.
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
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' ) );