WordPress Custom Field Conditional Statement

Subscribe

Building a WordPress site for a client recently, I needed the system to preform a series of steps:

  1. First, I needed WordPress to see see whether or not a certain custom field existed.
  2. If that field existed, I needed WordPress to echo the custom field’s value.
  3. 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"; }
}

Marketing Plan

Quimby Melton

Founder/President

Quimby is the founder and president of Studio Hyperset. He started Studio Hyperset in 2006 after studying Transatlantic literature and culture, new media, and humanities computing at the Universities of Georgia (AB, 00) and Nevada, Las Vegas (MA, 03; PhD, 08). He has a background in literary studies, media production, front-end development, and project management. His current primary duties involve helping clients frame solutions that meet their needs; scoping and managing Studio Hyperset's growth strategy and business development pipeline; finding and developing talent; and, most importantly, supporting the SH team.