• studiobarn

    (@studiobarn)


    Hi There

    Trying to work out the best way to achieve the following:

    I have 5 Custom post types. I would like to query all of these and display them in a grid. The grid will show one of each custom post type in a row, then repeat.

    Custom post types A, B, C, D, E

    Grid : A B C D E A B C D E A B C D E

    How can I achieve this?

    Thanks

Viewing 1 replies (of 1 total)
  • Howdy_McGee

    (@howdy_mcgee)

    Without playing with the SQL posts_where hook I don’t believe there’s anything built in to make things easy. Here’s something I put together but I haven’t tested it at all – lemme know if you run into issues:

    $query = new WP_Query( array(
    	'post_types'		=> array( 'cpt1', 'cpt2', 'cpt3' ),
    	'posts_per_page'	=> -1,
    ) );
    
    if( $query->have_posts() ) {
    	$post_types = array();
    	$tmp_posts  = array();
    
    	foreach( $query->posts as $post_obj ) {
    		$post_types[ $post_obj->post_type ][] = $post_obj;
    	}
    
    	$num_types = count( $post_types );
    
    	for( $i = 0, $x = 0; $i < $query->post_count; $i++, $x++ ) {
    		if( $x == $num_types ) {
    			$x = 0;
    		}
    
    		if( ! empty( $post_types[ $x ] ) {
    			$tmp_posts[] = array_shift( $post_types[ $x ] );
    		}
    	}
    
    	$query->posts = $tmp_posts;
    }
Viewing 1 replies (of 1 total)

The topic ‘Query multiple custom posts’ is closed to new replies.