PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 8, 2022

[FIXED] Query Custom Post Types & Order By Custom Post Type

 January 08, 2022     custom-post-type, wordpress     No comments   

Issue

Is it possible to query multiple CPTs and then order in a preset way?

For example, I have 2 CPTs & 1 being the WP default 'post' and would like the loop to return 6 results, ordering as below.

  • CPT-1
  • CPT-2
  • POST
  • CPT-1
  • CPT-2
  • POST

Is this possible without splitting the loop?

I did have a quick search, but could only find one article relating to this, the solutions from which don't appear to work any more...

Wordpress order posts by post type


Solution

Here is a shortened version of Sephsekla's code:

$my_post_types = array( 'CPT-1', 'CPT-2', 'post', 'CPT-1', 'CPT-2', 'post' );
$posts_shown = array();
$args = array(
    'post_type' => array( 'CPT-1', 'CPT-2', 'post' ),
    'post_status' => 'publish',
    'posts_per_page' => -1
);
$my_query = new WP_Query( $args );
foreach ( $my_post_types as $post_type ):
    while ( $my_query->have_posts() ): $my_query->the_post();
        if ( $post_type == get_post_type() && ! in_array( get_the_ID(), $posts_shown ) ) {
            echo '<pre>' . get_post_type() .': '. get_the_title() . '</pre>';
            $posts_shown[] = get_the_id();
            break;
        }
    endwhile;
    $my_query->rewind_posts();
endforeach;
wp_reset_postdata();


Answered By - Vayu Robins
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing