Custom Post Order for a Custom Post Type

I need a custom WP-Query written that will display a list of paginated pages (custom post type) in a custom order.

I have a custom post type called “courses”
I have a custom post type called “events”

The “courses” custom post type has a meta key called “course_id”.
The “events” custom post type has a meta key called “course_id”.

Currently, Im using code like the below to display a list of paginated “courses”.

$args = array(
    'post_type'=> 'courses',
    'order'    => 'DESC'
);
query_posts( $args );

// The Loop
while ( have_posts() ) : the_post();
    echo '<li>';
    the_title();
    echo '</li>';
endwhile;

// Reset Query
wp_reset_query();

What I would like to be able to do, is to display this same list of courses but ordered based on the number of related “events”.

Example:-

Course A -> course_id = A01
Course B -> course_id = B01
Course C -> course_id = C01

Event 01 -> course_id = A01
Event 02 -> course_id = A01
Event 03 -> course_id = B01
Event 04 -> course_id = B01
Event 05 -> course_id = B01
Event 06 -> course_id = C01

The custom WP Query will look at each “course” and course_id. It will then count the number of related “events” using the course_id as the unique key. The code would then output the “courses” as

Course B
Course A
Course C

or (if listed in ascending order):

Course C
Course A
Course B

To give you an idea of scale, there are likely to be about 200 different “courses”.
Each “course” is likely to have 20 – 200 “events” associated to it.

3 Answers
3

As it’s not clearly stated, how (in code) the “related” CPTs are interconnected, I want to post a mostly overseen possibility for CPTs.

When you register_post_type(), you have the argument of hierarchical that should be set to true to allow for 'supports' => array( 'page-attributes' ). This then allows you to define an order manually.

enter image description here

Leave a Comment