Support

Account

Home Forums General Issues Creating WP query with meta_query on array Reply To: Creating WP query with meta_query on array

  • You cannot do a query on this field in that way. In fact, I’m surprised that you first query works correctly. It should be something like this

    
    $postsargs = array(
    	'posts_per_page'   => 5,
    	'post_type'        => 'post',
    	'post_status'      => 'publish',
    	'meta_query'	=> array(
    		array( 
    			'key'	 	=> 'destinations', 
    			// not the " around the ID
    			'value'	  	=> '"'.$destid.'"', 
    			'compare' 	=> 'LIKE'
    		)
    	)
    );
    $getposts = get_posts( $postsargs );
    

    The only way that that your original query can work is if the ID number value is unique within the serialized array stored in the DB.

    ACF stores the field as a serialized array. To query for mulitple values requires doing something like this

    
    $postsargs = array(
    	'posts_per_page'   => 5,
    	'post_type'        => 'post',
    	'post_status'      => 'publish',
    	'meta_query'	=> array(
    		'relation' => 'OR',
    		array( 
    			'key'	 	=> 'destinations', 
    			'value'	  	=> '"'.$destinations_1_id.'"', 
    			'compare' 	=> 'LIKE'
    		),
    		array( 
    			'key'	 	=> 'destinations', 
    			'value'	  	=> '"'.$destinations_2_id.'"', 
    			'compare' 	=> 'LIKE'
    		),
    		// etc for each destination
    	)
    );
    $getposts = get_posts( $postsargs );
    

    With a lot of destinations this query will cause performance issues. My suggestion would be to set up a bidirectional relationship field for these posts.