Get user meta for only the keys with a certain prefix

There is a list of meta keys with the prefix my_theme, these are updated by the user. My problem is how to get_user_meta for only the keys with my_theme prefix. Tried a wildcard, didn’t work.

get_user_meta( $user_id, 'my_theme%', true  );

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

There is no native WordPress function to achieve this but you can get all meta keys for a given user ID and then filter the ones you need.

Here is how to do that for a given $user_id. First you get all the user meta entries:

$all_meta = get_user_meta($user_id);

As you can see in the get_user_meta() docs, since we are leaving the $key argument blank, this will contain an array with all the meta entries for the given user, including the ones you are looking for.

Then you may filter the resulting array with the PHP array_filter() function.

$only_my_theme_meta = array_filter($all_meta, function($key){
    return strpos($key, 'my_theme') === 0;
}, ARRAY_FILTER_USE_KEY);

Also note that each element is again an array, in some cases you may want to dereference the resulting array in order to take only the first index of each result:

$dereferenced_array = array_map(function( $a ){
return $a[0];
}, $only_my_theme_meta);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x