I want to see a list of registered custom post types within my Wordpress installation to quickly be able to write IF statements or any other functions targeting specific custom post types.
1 Answer
The following code lists all registered WP custom post types (only to admins) as an admin dashboard widget. Remember to enable the "Wordpress Custom Post Types" widget if it's hidden.
By default, the $cpt_remove variable has names of post types that I don't want shown, you can add more names to keep the list short.
Use this in your theme's functions.php or within a plugin:
add_action('wp_dashboard_setup', 'siv_admin_listall_cpts');
function siv_admin_listall_cpts() {
if( current_user_can('manage_options') ) {
wp_add_dashboard_widget(
'siv_list_cpts', // Widget slug.
'Wordpress Custom Post Types', // Title.
'siv_show_all_cpts' // Display function.
);
}
}
add_action( 'wp_dashboard_setup', 'siv_admin_listall_cpts' );
// Create the function to output the contents of our Dashboard Widget.
function siv_show_all_cpts() {
global $wp_post_types;
$posttypes = array_keys( $wp_post_types );
// Remove unwanted if any
$cpt_remove = array("attachment","nav_menu_item","customize_changeset","revision");
foreach ( $posttypes as $post_type ) {
if ( in_array($post_type, $cpt_remove) ) continue;
echo '<ul>';
echo '<li>'.$post_type.'</li>';
echo '</ul>';
}
}
I hope others find this of use as I know I, as a beginner, have spent a lot of time trying to figure out the slug is in different occasions.