简体   繁体   English

缺少字段时如何使用 php 或 js 回显默认文本?

[英]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 '所以我想回应类似“如果自定义字段存在 = <?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.我想可以在 php 和 javascript 中以两种方式进行,但我不知道如何以两种方式键入代码,因为我仍然是一个新手。 Can you please help me?你能帮我么? Thanks in advance!提前致谢!

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 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.因为我知道get_post_meta($post->ID, 'mycustomfield', true)是返回您的自定义字段的原因。

In PHP +7 and major, if your variable contains the data you want to output you could use the null coalescing operator .在 PHP +7 和主要版本中,如果您的变量包含要输出的数据,则可以使用空合并运算符

echo $customField ?? 'hello';

This will output $customField if it exists, or hello if it doesn't.这将输出$customField如果它存在,或者hello如果它不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM