I have a WP Query that is checking a custom post types metafields.
I have two custom post types:
- Country
- Media
The country custom posts type is simply created to pull the content of the media post type into.
The Media CPT contains 2 metafields:
- The first metafield is a media filter selection that allows the selection of "TV", "Radio", "Digital" and has this ID
_rtl_media_filter
. - The second contains a country to associate the post type to and has this ID
_rtl_country_filter
, which is pulling the country CPT name into a dropdown and can be selected from within the media post type.
The aim is to display all the media types that are assiciated with the country CPT when the country CPT is viewed.
I have this loop, which works. But am wondering if I can group a single loops item by media type _rtl_media_filter
? Rather than creating multiple loops for each?
<?php
// Grab this posts ID
$post = $wp_query->post;
$this_id = $post->ID;
// Query the meta vaules against the posts ID
$args = array(
'post_type' => 'media',
'meta_query' => array(
'relation' => 'OR',
array( // TV
'relation' => 'AND',
array(
'key' => '_rtl_media_filter',
'value' => 'tv',
'compare' => '=',
),
array(
'key' => '_rtl_country_filter',
'value' => $this_id,
'compare' => '=',
),
),
array( // DIGITAL
'relation' => 'AND',
array(
'key' => '_rtl_media_filter',
'value' => 'digital',
'compare' => '=',
),
array(
'key' => '_rtl_country_filter',
'value' => $this_id,
'compare' => '=',
),
),
array( // RADIO
'relation' => 'AND',
array(
'key' => '_rtl_media_filter',
'value' => 'radio',
'compare' => '=',
),
array(
'key' => '_rtl_country_filter',
'value' => $this_id,
'compare' => '=',
),
),
),
'posts_per_page' => -1,
);
$the_query = new WP_Query( $args );
if($the_query -> have_posts()) :
while ($the_query -> have_posts()) : $the_query -> the_post();
echo '<h2>' . the_title() . '</h2>';
endwhile;
wp_reset_postdata();
endif;
?>
This is how I would like the output:
|TV|
ITV | ITV2 | ITV3
|RADIO|
Radio 1 | Radio2
|DIGITAL|
HUB 1 | HUB 2