Question

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  );
Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top