WP_Query 当元值保存为序列化数组时

Rah*_*eel 5 php wordpress wordpress-theming

我正在手动获取 woocommerce 产品。

问题是我在产品上有一个自定义字段,即 _locations。一个产品可以属于多个位置,所以我在 wp-admin 的产品添加表单中提供了一个多选列表。

下面是我用来保存 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 )) );
}
Run Code Online (Sandbox Code Playgroud)

请注意,我已经序列化了 meta_value 的数据,因此我只有一个唯一键_locations,所有位置值都与之关联。

现在在我取货时出现问题

$args = array(
      'post_type' => 'product',
      'product_cat' => $food_category->slug,
      'meta_key' => '_locations', 
      'meta_value' => 'newyork'   
     );
     $loop = new WP_Query($args);
Run Code Online (Sandbox Code Playgroud)

我只想获取产品newyork但在数据库中它存储为序列化数组

s:69:"a:2:{i:0;s:7:"newyork";i:1;s:13:"massachusetts";}";
Run Code Online (Sandbox Code Playgroud)

我怎样才能让这个查询只获取纽约产品。

谢谢

Dav*_*vid 5

尝试:

$args = array(
  'post_type' => 'product',
  'product_cat' => $food_category->slug,
  'meta_query' => array(
     array(
        'key'     => '_location',
        'value'   => '%newyork%',
        'compare' => 'LIKE',
     ),
   ),
 );
Run Code Online (Sandbox Code Playgroud)

  • 根据我的经验,我认为 % 是自动添加的,所以不需要写 %newyork% (2认同)