0

I have a custom post type which has an array as a meta data. Here's how it looks inside wp_postmeta table.

  • meta_key: _allowed_companies
  • meta_value: a:2:{i:0;s:3:"275";i:1;s:4:"8386";}

Obviously, this _allowed_companies meta is an array with two values of 275 and 8386, each representing a post ID of a company.

On front-end, I wish to display a list of items filtered by the allowed company. Say, in a form, if I choose company 275 and click submit, then all the items which has 275 inside its _allowed_companies meta will be displayed.

This is what I tried but in vain: (Below code uses two query conditions of _item_type and _item_allowed_companies. _item_type is a plain string and works fine, but the problem kid is _item_allowed_companies.)

$item_type = 'Assets';
$allowed_company = 275;

$meta_array = array();
$meta_array = array( 'relation' => 'AND' );
if( $item_type ) $meta_array[] = array( 'key' => '_item_type', 'value' => $item_type, 'compare' => '=' );
if( $allowed_company ) $meta_array[] = array( 'key' => '_item_allowed_companies', 'value' => $allowed_company, 'compare' => 'IN' );

$args = array( 
  'post_type'       => 'item',
  'post_status'     => 'publish',
  'posts_per_page'  => $posts_per_page,
  'paged'           => $paged,
  'meta_query'      => $meta_array
);

I think the use of compare operator of IN is wrong here, but have no idea how to alter it.

0

You can make use of REGEXP operator in META_COMPARE.

For example:

$meta_array[] = array( 
    'key' => '_item_allowed_companies', 
    'value' => $allowed_company, 
    'compare' => 'REGEXP' 
);

$args = array( 
    'post_type'         => 'item',
    'post_status'       => 'publish',
    'posts_per_page'    => $posts_per_page,
    'paged'             => $paged,
    'meta_query'        => $meta_array
);

References:

  • This is great and works like a charm! Yeah, I saw 'REGEXP' operator in wordpress codex, but had no idea what that means and didn't try that one. So cool. Thank you, Udit, and thank you Pieter. – Dongsan Nov 9 '14 at 22:50
  • It's my Pleasure. Glad that it helped :) – Udit Desai Nov 17 '14 at 12:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.