Get list of all registered post types slugs

admin2025-01-07  4

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!

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!

Share Improve this question asked Nov 21, 2011 at 19:18 unfulviounfulvio 1,8247 gold badges32 silver badges63 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 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;
        }
    }
}

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, 'objects' ); // 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.
    }
}
?>

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.

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' ) );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736258336a505.html

最新回复(0)