WordPress Custom Field Conditional Statement

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"; }
}

Exit mobile version