0

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!

oktapodia
  • 1,695
  • 1
  • 15
  • 31
  • 3
    Have you done any research into the syntax for writing conditional statements for either language? You seem to know the logic that you want, so it's not really clear what trouble you're having aside from not trying anything. – Patrick Q Jan 14 '20 at 14:27

2 Answers2

1

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.

jeprubio
  • 17,312
  • 5
  • 45
  • 56
1

In PHP +7 and major, if your variable contains the data you want to output you could use the null coalescing operator.

echo $customField ?? 'hello';

This will output $customField if it exists, or hello if it doesn't.

Emiliano
  • 698
  • 9
  • 30
mark_b
  • 1,393
  • 10
  • 18