How to List All Custom Post Types Names (Not Posts)

Having Some Custom Post Types Like "Projects", "Products" and "Events" I need to list them in a page. Please be advis that I do not want to list any POST here! instead I just want query the name of all Custom post type and Link them into archive-projects.php, archive-products.php and archive-events.php for each of them. Can you please let me know how to do that?
Thanks

1 Answer
1

Get all custom post types:

$post_types = get_post_types( array ( '_builtin' => FALSE ), 'objects' );

Sort them by their name:

uasort( $post_types, 'sort_cpts_by_label' );

/**
 * Sort post types by their display label.
 *
 * @param object $cpt1
 * @param object $cpt2
 * @return int
 */
function sort_cpts_by_label( $cpt1, $cpt2 ) {

    return strcasecmp(
        $cpt1->labels->name,
        $cpt2->labels->name
    );
}

Link the post type names to their archives if archives are actually available:

foreach ( $post_types as $post_type => $properties ) {
    if ( $properties->has_archive ) {
        printf(
            '<a href="https://wordpress.stackexchange.com/questions/175365/%1$s">%2$s</a><br>',
            get_post_type_archive_link( $post_type ),
            $properties->labels->name
        );
    }
}

Leave a Comment