Support

Account

Home Forums ACF PRO Test that Relationship Field has at least one Result

Solving

Test that Relationship Field has at least one Result

  • I am using the following code to output information about the items selected in a Relationship field. This code works perfectly in selecting the items on the right side of the Relationship control, as long as at least 1 item was selected. If no items were selected (no results), the code returns all the input to the control (every value on the left). That seems like unexpected behavior, to me. Does anyone know how to test to make sure there is at least one item selected (1 result) from a relationship control?

    $ids = get_field(‘dl_interested_in’,false,false);

    $args = array(
    ‘numberposts’ => -1,
    ‘post_type’ => ‘daylily’, //my custom post type
    ‘include’ => $ids,
    ‘orderby’ => ‘title’,
    ‘order’ => ‘ASC’,
    );

    $wishlistitems = get_posts($args);

  • Hi @darusharp

    When passing an empty array to ‘include’, all results are returned…
    .. which I guess is what you are saying 🙂

    I tested the above scenario, and when no posts are chosen, $ids is in fact empty…

    You can test if it *has* any values by doing:

    
    if ($ids) {
      $args = array(
        'numberposts' => -1,
        'post_type' => 'daylily', //my custom post type
        'include' => $ids,
        'orderby' => 'title',
        'order' => 'ASC',
      );
      $wishlistitems = get_posts($args);
    } else {
      echo 'No one is wishing for anything at the moment';
    }
    

    Hope that helps!

  • OK! Thank you so much! I wasn’t aware of that behavior when passing an empty array to include.

    Thanks for your very speedy response.

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Test that Relationship Field has at least one Result’ is closed to new replies.