Match values from two arrays to return posts. wp_query?
-
I’ve been trying to solve this problem for a couple of days. I am using custom post types and advanced custom fields and what I am trying to do is return posts where values from a custom field from one custom post type match values on anotehr custom field from another custom post type.
My set up is like this:
custom post type1: ‘stores’
acf field1: ‘store_brands’ (text field) comma seperated values e.g. (Asda, Morrisons, Sainsburys)custom post type2: ‘brands’
acf field1: ‘brand_name’ (text field) one values e.g. (Ford)
acf field2: ‘brands_name_alt’ (text field) comma seperated values e.g. (FordCar, Fored)I have been using wp_wuery. I nearly got it working, but not quite. It worked when single values were in brands_name_alt. but not if there was multiple values e.g (FordCar, Fored).
The code I had so far in the stores post template is:
$list = get_field( "store_brands" ); $array = explode(',', $list); $args = array( 'post_type' => array('stores', 'brands'), 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'brand_name', 'value' => $array, 'compare' => 'IN' ), array( 'key' => 'brands_name_alt', 'value' => $array, 'compare' => 'IN' ), ), ); $custom_query = new WP_Query($args); while($custom_query->have_posts()) : $custom_query->the_post(); ?>
This works if there is a single value in the brands_name_alt. But not otherwise.
I guess what I need to be able to do is compare two arrays and return posts where there is a match. It would work if I could use the ‘LIKE’ comapre, but this is not possible with an array value.
Is there another approach I could take to this? I know storing the values this way is messy. But its the easiest way as there could be 100’s of store_brands.
- The topic ‘Match values from two arrays to return posts. wp_query?’ is closed to new replies.