I'm trying to query the list of posts using the meta_key but the result I got back was an empty array.
To write the data, I used the following codes:
$post_id = 2;
$user_key = 'ldp_system_follows_user_1';
$user_data_new = array(
'followed' => 'nofollowed'
);
update_post_meta($post_id, $user_key, $user_data_new);
The above code persisted the following in db when executing get_post_meta(post_id);
{
"ldp_system_follows_user_1": [
"a:1:{s:8:\"followed\";s:8:\"followed\";}"
]
}
I wanted to retrieve all the post ids that matches the meta data I wrote but it returned an empty array.
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => $user_key,
'value' => $user_data_new,
'compare' => 'LIKE'
))
);
return get_posts($args);
Any help would be greatly appreciated.
UPDATE 1:
As suggested by phatskat, here are the SQL statement when I changed 'value' => 'follow'
and 'value' => 'nofollow'
respectively. However, I'm still getting the empty array back:
//'value' => $user_data_new,
"query": {
"post_type": "post",
"post_status": "publish",
"meta_query": [
{
"key": "ldp_system_follows_user_1",
"value": {
"followed": "nofollowed"
},
"compare": "LIKE"
}
]
},
"request": "SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND ( \n ( wp_postmeta.meta_key = 'ldp_system_follows_user_1' AND CAST(wp_postmeta.meta_value AS CHAR) LIKE '%followed%' )\n) AND wp_posts.post_type = 'post' AND ((wp_posts.post_status = 'publish')) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10",
"request": "SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND ( \n ( wp_postmeta.meta_key = 'ldp_system_follows_user_1' AND CAST(wp_postmeta.meta_value AS CHAR) LIKE '%nofollowed%' )\n) AND wp_posts.post_type = 'post' AND ((wp_posts.post_status = 'publish')) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10",
$user_data_new
in your query? According to the code from earlier, it's an array, but in the WP_Query docs: "value (string|array) - Custom field value. It can be an array only when compare is 'IN', 'NOT IN', 'BETWEEN', or 'NOT BETWEEN'.." Emphasis mine. It looks like, if you're doing LIKE with an array, it won't work.$user_data_new = array('followed' => 'nofollowed');
is an array in my query. I changed'compare' => 'IN'
but I'm getting an empty result.