I have two custom post types, “companies” and “deals”. These are set as a relationship, where each deal can be set to a specific company.
I am trying to get a custom loop on the homepage, where I display the deals. However, I only want to show one deal per company. If a new deal is added, I want it to placed at the beginning of the loop, and if the company that deal was assigned to already had another deal in the loop, that post should disappear.
I currently have the following code:
<?php
$num_cats_to_show = 50;
$count = 0;
$posts = new WP_Query(array('post_type' => 'companies'));
$terms = $posts->get_posts();
if ($terms) {
foreach( $terms as $term ) {
$args2=array(
'post_type' => 'deals',
'meta_query' => array(
array(
'key' => 'company', // name of custom field
'value' => '"'. ($term->ID) .'"', // matches exaclty "123", not just 123. This prevents a match for "1234"
'compare' => 'LIKE'
)
),
'posts_per_page' => 1,
);
$my_query = null;
$my_query = new WP_Query($args2);
if( $my_query->have_posts() ) {
$count ++;
if ($count <= $num_cats_to_show) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<?php echo $term->ID ?><p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
<?php
endwhile;
}
}
}
}
wp_reset_query(); // Restore global post data stomped by the_post().
?>
This almost works, however it gets sorted by the post type ‘companies’, and not by deal.
Anybody can help me out with this?