-2

Hope that title makes sense, I have a few meta fields that I want to output 0 if they are empty.

I'm currently outputting the values with this:

<?php meta('some-field'); ?>

Edit: the above code will echo out the value

3 Answers3

1

For example use the ternary operator. After PHP 5.3:

echo meta('some-field') ? : 0;

Before PHP 5.3:

echo meta('some-field') ? meta('some-field') : 0;
Gerifield
  • 403
  • 5
  • 12
1

assuming meta() write and not return anything...

function callback($buffer) {
    // check if buffer is empty, else return 0
    return (!empty($buffer)) ? $buffer : 0;
}

// turn output buffering on. the output is stored in an internal buffer. 
// The callback function will be called when the output buffer is flushed
ob_start('callback');

meta('some-field');

// Flush the output buffer
ob_end_flush();

working example: http://phpfiddle.org/main/code/42rr-zh8j


assuming meta() return value and not write anything...

// Check if meta return value is empty, print meta value else print 0
echo ( !empty(meta('some-field')) ) ? meta('some-field') : 0;
Simone Nigro
  • 4,717
  • 2
  • 37
  • 72
0

you can wrap meta() in a custom function of your own:

function myMeta($key, $default = '0') {
   $meta = meta($key);
   return empty($meta) ? $default : $meta;
}

and use it instead of meta:

myMeta('some-field');
myMeta('some-field', 'other-default-value');
Waldson Patricio
  • 1,489
  • 13
  • 17