Home Forums General Issues Create loop of posts with relationship field; only show one per field


Create loop of posts with relationship field; only show one per field

  • 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:

    	$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 ) {
    	      'post_type' => 'deals',
    	      'meta_query' => 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>
    	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?

  • Hi @teun

    Could you please share the JSON or XML export file of your field group so I can test it out on my end?

    Thanks 🙂

  • Hi,

    I actually solved it by making an array and then check for duplicate custom fields, like so:

    $args         = array(
        'post_type' => 'deals'
    $the_query    = new WP_Query($args);
    $unieke_deals = array();
    if ($the_query->have_posts()):
        while ($the_query->have_posts()):
            $bedrijf = get_field('company');
            if (!in_array($bedrijf, $unieke_deals)):
                $unieke_deals[] = $bedrijf;
    <?php the_field('company'); ?>
    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><br />
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.