Support

Account

Home Forums Front-end Issues Wp_query with relationship to another custom post type Reply To: Wp_query with relationship to another custom post type

  • Sure, I will cobble some code together below. May need some tweaks 🙂

    
    $args = array(
      'post_type' => 'hospital',
      'posts_per_page' => 10, // you could use -1 for 'all'
      'meta_query' => array(
        array(
          'key' => 'recommended',
          'value' => TRUE,
          'compare' => '=',
        ),
      ),
    );
    $the_query = new WP_Query( $args );
    
    $all_branch_ids = array();
    if ( $the_query->have_posts() ) {
      while ( $the_query->have_posts() ) {
        $the_query->the_post();
          $all_branch_ids = array_merge( $all_branch_ids, get_field('branch_id_field') ); // this *should* work (untested)
      }
      wp_reset_postdata();
    }
    // Essentially, with the above, we are looping through 'hospital' records and appending the array of "branch ids" (from the relationship field) to an array of "all" bracnch ids. This *could* potentially introduce duplicates, for which we address below.
    Of course, we are only getting "branch ids" that are *recommended*, because the Hospital Query only returns recommended hospitals.
    
    $all_branch_ids = array_unique($all_branch_ids); // remove duplicates
    
    // Now, we can query branches using: post__in
    
    $args = array(
      'post_type' => 'branch_clinic',
      'posts_per_page' => -1, // use -1 for 'all'
      'post__in' => $all_branch_ids // has to be array like: array( 2, 5, 12, 14, 20 )
    );
    $the_query = new WP_Query( $args );
    

    Note that empty arrays passed to ‘post__in’ can have undesired results, and there is a special note to be made about ‘sticky posts’ when using ‘post__in’

    I encourage you read this entire page: https://codex.wordpress.org/Class_Reference/WP_Query