0

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  );

1 Answer 1

2

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);
1
  • Awesome, this just put me in the right direction. And definitely getting somewhere with your answers. Thanks! May 9, 2021 at 8:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.