Loop that displays the first post of every available custom post type?

Is it possible to create a loop that goes through all the available custom post types without statically defining what those custom post types are, and then displaying the featured image of the first post for each of those custom post types?

Related posts

Leave a Reply

2 comments

  1. This should work for you:

    // grab all public post types
    $post_types = get_post_types( array('public' => true), 'names' );
    
    // loops through each post type
    foreach( $post_types as $type ) {
    
        // setup the query
        $query_args = array(
            'post_type' => $type,
            'posts_per_page' => 1
        );
    
        // perform the query
        $items = get_posts( $query_args );
    
        // check if we have found anything
        if( $items ) {
    
            // loop through the items
            foreach( $items as $item ) {
    
                // show the post thumbnail
                echo get_the_post_thumbnail( $item->ID, 'thumbnail' );
    
            }
    
        }
    
    }
    
  2. As an addition to @Pippin answer:

    It is even possible to use a single query, with a slightly different syntax.

    // Get all post types
    $post_types = get_post_types( 
         array( 
             'public'       => true
             // Avoid attachments - those aren't shown in the admin menu
            ,'show_in_menu' => true 
         )
        ,'names'
    );
    
    // Get rid of unwanted post types
    // Use the array to add your unwanted post types
    foreach ( array( 'some_unwanted_post_type', 'another_one' ) as $not_me )
        in_array( $not_me, $post_types ) AND unset( $post_types[ $not_me ] );
    
    // Group by filter
    add_filter( 'posts_groupby', 'wpse57806_posts_groupby', 20 );
    
    // Query posts - Two options for post_types
    $items = get_posts( array(
         'post_type'      => $post_types
        // ... or ...
        # 'post_type'       => 'any' // every post type, but not attachments
        ,'posts_per_page' => count( $post_types )
    ) );
    
    // Call the thumbnail
    foreach ( $items as $item )
        echo get_the_post_thumbnail( $item->ID, 'thumbnail' );
    

    Edit

    You’ll need a small callback function to make the edit work:

    function wpse57806_posts_groupby()
    {
        // only needed once - better kept in here
        remove_filter( current_filter(), __FUNCTION__ );
    
        return 'post_type';
    }