I try to get posts that either do not have a custom field set or if set have a value not like a given parameter.
Here is my code:
$args_included = array(
'numberposts' => 1,
'post_type' => 'post',
'post_status' => 'published',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'requested_by',
'value' => '%' . $SANITIZED_PARAM . '%',
'compare' => 'NOT LIKE'
),
array(
'key' => 'requested_by',
'compare' => 'NOT EXISTS'
)
)
);
get_posts($args_included); // empty array
The custom field requested_by
is supposed to be either empty or filled with a string value like this one : foo;bar;gamma;
.
If I remove this part of the code :
'relation' => 'OR',
array(
'key' => 'requested_by',
'value' => '%' . $SANITIZED_PARAM . '%',
'compare' => 'NOT LIKE'
),
the query then works.
What am I missing ?
WP 3.5
UPDATE Here is my final code that work :
$args_included = array(
'numberposts' => 1,
'post_type' => 'post',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'requested_by',
'value' => $PARAM,
'compare' => 'NOT LIKE'
)
)
);
get_posts($args_included); // Just ONE post
Mistakes:
- Status is
publish
notpublished
The custom field didn't exist so no results can be found.
Below is a SQL query for mass setting the custom field:INSERT INTO wp_postmeta(post_id,meta_key,meta_value) SELECT ID , 'requested_by', ';' FROM wp_posts WHERE post_status='publish' AND post_type='post'
Last tips for debug purpose. You can get the final SQL query sent to MySQL like this:
$args = array( 'numberposts' => 1, 'post_type' => 'post', 'post_status' => 'publish', 'meta_query' => array( array( 'key' => 'requested_by', 'value' => $PARAM, 'compare' => 'NOT LIKE' ) ) ); $q = new WP_Query($args); echo $q->request;