Another slight improvement from @sMyles' answer.
I have had cases where IDs have been stored both as strings (such as when taken from a form input) and as integers (e.g. update_post_meta($post_id, authorized_users', array(get_current_user_id()));
). This is kind of like the well-known issue with wp_set_object_terms()
where you can use term IDs to set the terms, but if you don't cast them as integers first you stand about a 50% chance of creating new terms with those numbers as their names instead.
This can result in them being stored quite differently in a serialized array, as can be seen from the excerpts of just such a case from my test site's database:
a:1:{i:0;s:1:"1";} // 's' for 'string', also note the double quotes
a:1:{i:0;i:1;} // 'i' for 'integer', no quotes
Both of the above, when fed through print_r()
will render as
Array
(
[0] => 1
)
To fix this, I made a slight tweak to the meta_query
by adding a relation
and another version of the query that cast the value as an integer instead of a string.
Here's the final result:
'meta_query' => array(
'relation' => 'OR', // Lets it know that either of the following is acceptable
array(
'key' => 'bcm_enm_authorized_users',
'value' => serialize(strval(get_current_user_id())), // Saved as string
'compare' => 'LIKE'
),
array(
'key' => 'bcm_enm_authorized_users',
'value' => serialize(intval(get_current_user_id())), // Saved as integer
'compare' => 'LIKE'
),
),
EDIT: Just realized that this method could run the risk of collisions with array indexes, which could allow someone illicit access to materials if they're not in the array, but their user ID appears as an index. As such, while this works if you have the issue discussed, better practice is to ensure that any values you want to search for are cast as strings prior to saving them so that you can use @sMyles' method instead.