Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WP_Query when meta_value saved as serialized array

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

like image 233
Raheel Avatar asked Sep 29 '22 15:09

Raheel


2 Answers

try:

$args = array(
  'post_type' => 'product',
  'product_cat' => $food_category->slug,
  'meta_query' => array(
     array(
        'key'     => '_location',
        'value'   => '%newyork%',
        'compare' => 'LIKE',
     ),
   ),
 );
like image 167
David Avatar answered Oct 02 '22 17:10

David


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',
     ),
   ),
 );
like image 23
Purvik Dhorajiya Avatar answered Oct 02 '22 15:10

Purvik Dhorajiya