[HELP] Display Custom Post Type on archive page grouped by ACF relationship

I have a custom post category archive and I want to group each post by an ACF relationship field. Here’s a simple visual example of what I mean:

MUSIC VIDEOS ARCHIVE

—————-
Alan Jackson

CPT Post
CPT Post
CPT Post

—————-
Frank Sinatra

CPT Post
CPT Post
CPT Post

—————-
Michael Jackson

CPT Post
CPT Post
CPT Post

That is a simple example, although it doesn’t reflect exactly what I’m working with. In my situation, I created an archive page in Elementor for the “**episodes**” category of the “**videos**” CPT. I need to display all episodes grouped by ACF relationship “**guest**” which is another CPT.

How can I do this?

## ALGORITHM

Get all Guests
Sort Guests list Alphabetically ascending
Loop through each guest cpt

If Guest has related episodes
Display Guest Name in an H2 tag
Loop through and display all episodes connected (via ACF relationship field) with current guest, by date posted and post ID

If multiple episodes are posted for the guest on the same date
sort posts for date by post ID
END IF
END IF

END LOOP

## MY CODE

I’ve cobbled this code snippet together after reading docs and different articles online, but it is not working:

function videos_query($args) {

$videos_query = [];

$the_query = get_posts(‘post_type=videos’);

foreach ( $the_query as $post ) : setup_postdata( $post );
$videos_query[] = array(
‘id’ => get_post_meta(get_the_ID(), ‘idkey’, true ),
‘field1’ => get_post_meta(get_the_ID(), ‘field1key’, true ),
‘title’ => get_the_title($post->ID)
);
endforeach;
wp_reset_postdata();
return $videos_query;
}

function wpc_elementor_shortcode( $atts ) {

// $query = new WP_Query( array( ‘author’ => 1 ) );

// echo “<h3>Query Results Count: ” . count($query) . “</h3>”;

// $post_types = get_post_types();
// echo “<pre>”;
// var_dump($post_types);
// echo “</pre>”;
//

$videos_results = videos_query();

$vidCount = count($videos_results);

echo “<h3>Video Count: $vidCount</h3>”;

}
add_shortcode( ‘my_elementor_php_output’, ‘wpc_elementor_shortcode’);

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer