I am fetching woocommerce products manually.
The problem is that i have a custom field on products i.e _locations. A product can belong to multiple locations so i provided a multi select list in the product adding form in wp-admin.
Below is the function by which i am saving the meta_value
function woo_add_custom_general_fields_save( $post_id ){
// Select
$woocommerce_select = $_POST['_locations'];
if( !empty( $woocommerce_select ) )
update_post_meta( $post_id, '_locations', esc_attr(maybe_serialize($woocommerce_select )) );
}
Notice i have serialzed the data for meta_value so that i have only one unique key _locations
with all locations values associated with it.
Now the problem occurs when i am fetching products
$args = array(
'post_type' => 'product',
'product_cat' => $food_category->slug,
'meta_key' => '_locations',
'meta_value' => 'newyork'
);
$loop = new WP_Query($args);
I want to get products only for newyork
but in the database it is stored as serialzed array
s:69:"a:2:{i:0;s:7:"newyork";i:1;s:13:"massachusetts";}";
How can i make this query fetch only newyork products.
Thanks
try:
$args = array(
'post_type' => 'product',
'product_cat' => $food_category->slug,
'meta_query' => array(
array(
'key' => '_location',
'value' => '%newyork%',
'compare' => 'LIKE',
),
),
);
I had a similar problem and I solved it using the serialize()
. Below is the example.
$args = array(
'post_type' => 'product',
'product_cat' => $food_category->slug,
'meta_query' => array(
array(
'key' => '_location',
'value' => serialize( array( 'newyork' ) ),
'compare' => 'LIKE',
),
),
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With