Skip to content
Advertisement

How to use php or js to echo a default text when a field is missing?

I’m using custom field data, but a couple of posts have a certain custom fields empty.

So I’d like to echo something like “if custom field exists = <?php echo get_post_meta($post->ID, 'mycustomfield', true); ?> else = ‘hello

I suppose it’s possible to do it both ways in php and javascript but I have no idea how to type the code in both way, as I’m still a fresh newbie. Can you please help me? Thanks in advance!

Advertisement

Answer

You mean something like:

echo get_post_meta($post->ID, 'mycustomfield', true) ? 
    get_post_meta($post->ID, 'mycustomfield', true) : 'helo';

or the same assigning to a $customField var:

$customField = get_post_meta($post->ID, 'mycustomfield', true);
echo $customField ? customField : 'helo';

?

This is done, in this example, using the ternary operator which seems to fit in what you ask for.

Because I understand that get_post_meta($post->ID, 'mycustomfield', true) is what returns your custom field.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement