I find it annoying that functions like get_user_meta
or get_post_meta
will return an array if the meta key exists or false if it doesn’t. This means I need to do a check like so:
$meta = get_post_meta($id, $meta_key);
if ($meta) {
foreach ($meta as $value) {
// ...
}
}
I was hoping for a way where I wouldn’t have to check if it’s not a falsy value first.
I normalize the output of these functions using this logic:
(array) false
becomesarray (false)
.array_filter
, which, when not passed a callable, simply filters falsy values from the array.Here is this logic in action:
Warning: This will strip all falsy values, e.g. if your meta value is zero or an empty string, it will be not be iterated through.
If you always need an array, just use
get_post_custom( get_the_ID() )
and extract the value that you need by key.Your return value will either be
FALSE
(so you can test with!
against it), or your value.get_post_meta()
does not returnfalse
if the key doesn’t exist.If you look at the source, you will see that
get_post_meta()
is a wrapper aroundget_metadata()
which is used to retrieve data in several different contexts.get_metadata()
will returnfalse
if you give it very bad information, but that should never happen with theget_post_meta()
wrapper unless the ID is not set or is empty or is set to something that won’t caste to an int. For example:Or
Or
Whereas, setting
$id
to any integer or numeric string will result in an empty array.Your analysis of the function is wrong. Whatever is going wrong with your code is going wrong before the call to
get_post_meta()
. You really should be checking that$id
is correct before trying to use it.From another perspective, simply returning an empty array for all case would be providing less feedback, less information, for applications that need it. If you don’t need the extra feedback the code is trivial and can be don in several ways. I prefer:
But if your PHP is recent enough, you could also use a shortcut ternary, which makes for very succinct code: