WordPress Custom Field Conditional Statement
by
Quimby Melton
May 26, 2012 | Leave a comment
Updated May 26, 2012
Building a WordPress site for a client recently, I needed the system to preform a series of steps:
- First, I needed WordPress to see see whether or not a certain custom field existed.
- If that field existed, I needed WordPress to echo the custom field’s value.
- If the custom field did not exist, I needed WordPress to echo a bit of default text.
Unable to find any substantial leads in the WordPress Codex or elsewhere, I tried a few methods, and the following seemed to work best, albeit in the inverse of the way I originally conceived the request.
Originally, I semantically scoped the statement as,
“If custom field x exists, echo the custom field value, else echo a bit of default text.”
Instead, I wound up asking WordPress,
“If custom field x doesn’t exist, echo a bit of default text, else echo the custom field value.”
I’ve shared the final conditional statement below in case it helps anyone else.
$key_values = get_post_custom_values('CUSTOM-VALUE-NAME');
if ($key_values == '') {
echo "DEFAULT TEXT"; }
else {
foreach ( $key_values as $key => $value ) {
echo "$value"; }
}
Get the most out of your online marketing efforts
Set Your Words on Fire
Studio Hyperset’s master guide to content, platforms, and the contemporary marketing pipeline.