Reputation: 1322
I am trying to query posts with meta_query
filter but the problem is I have stored multiple user ID's on custom field and I can't figure out how to filter the posts.
So the custom field is multi select box, and it saves ID's of selected users.
Now on the front end I want to query posts by checking if currently logged in user is in the list of selected users.
The query looks like this:
$args = array(
'post_type' => 'music',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'manager',
'value' => get_current_user_id(),
'compare' => 'LIKE',
),
)
);
$loop = new WP_Query( $args );
This would work if I have single user ID in the field. But value of manager
is an array.
EDIT: To add a bit more info, the value of the field is saved as serialized array so the value in database is:
a:2:{i:0;s:1:"2";i:1;s:1:"5";}
The value to compare is just currently logged user id so it would be 5
for example.
If current user 5
is in serialized data query the post.
Upvotes: 0
Views: 1954
Reputation: 3572
Meta values are strings, so you can't build query where they behave like an array. For WP_Query there is IN operator, but that is for vice-versa cases (when meta_value should be inside the given array).
So, to achieve your goal you can use some SQL. Find matched posts using SQL, then pass found post ID-s to WP_Query.
global $wpdb;
$sql="SELECT post_id FROM $wpdb->postmeta
WHERE meta_key='manager'
AND meta_value like '%:".'"'.esc_sql($user_id_here).'"'.";%'";
$found_posts=$wpdb->get_col($sql);
if(empty($found_posts))$found_posts=[0];
$args = array(
'post_type' => 'music',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
'post__in'=>$found_posts
);
$loop = new WP_Query( $args );
Upvotes: 1