Support

Account

Home Forums ACF PRO Relationship Using WP_Query arguments

Solved

Relationship Using WP_Query arguments

  • I have followed the example set out on the Relationship document page to load only selected post ID’s.

    // get only first 3 results
    $ids = get_field('conference_talks', false, false);
    
    $query = new WP_Query(array(
    	'post_type'      	=> 'conferences',
    	'posts_per_page'	=> 3,
    	'post__in'		=> $ids,
    	'post_status'		=> 'any',
    	'orderby'        	=> 'rand',
    ));

    This works correctly if posts are selected in the relationship field. However if no posts are selected the query outputs 3 posts. Surely if nothing is selected nothing should be output?

    Any help/pointers appreciated.

  • Hi @cultivate,

    Thanks for the post.

    In this use case, I would recommend you make use of a conditional block to check if there is any value from the get_field() and then run the query.

    The code would look like so:

    // get only first 3 results
    if(get_field('conference_talks'){
    $ids = get_field('conference_talks', false, false);
    
    $query = new WP_Query(array(
    	'post_type'      	=> 'conferences',
    	'posts_per_page'	=> 3,
    	'post__in'		=> $ids,
    	'post_status'		=> 'any',
    	'orderby'        	=> 'rand',
    ));}
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.