如果两个自定义字段中有一个为空,则隐藏文本

时间:2018-03-02 作者:user6744245

我将自定义字段调用到我的页面模板中,如下所示:

the team donated
<!-- display funds raised -->
<?php $givingback_details_funds = get_post_meta($post->ID,\'givingback_details_funds\', true); if ($givingback_details_funds == \'\') { ?>
<!-- display nothing if there is no entry for funds raised -->
<?php } else { ?>
<!-- display this if there is another entry -->
<?php echo get_post_meta($post->ID, \'givingback_details_funds\', true); ?>
<?php } ?>
<!-- display days donated -->
<?php $givingback_details_days = get_post_meta($post->ID, \'givingback_details_days\', true); if ($givingback_details_days == \'\') { ?>
<!-- display nothing if there is no entry for days donated -->
<?php } elseif ( isset($givingback_details_days) && $givingback_details_days == "1" ) { ?>
<!-- display this if entry for day is \'1\' -->
one working day
<?php } else { ?>
<!-- display this if there is another entry -->
<?php echo $givingback_details_days ?> working days
<?php } ?>
如果帖子只有一个值,这将显示很棒。示例:“团队捐赠了300英镑”或“团队捐赠了一个工作日”。

但我不知道如何让“and”这个词出现在这两个值之间。示例:“团队捐赠了300英镑和一个工作日”,而不是“团队捐赠了300英镑一个工作日”。

1 个回复
最合适的回答,由SO网友:Jacob Peattie 整理而成

PHP函数implode() 允许您从一个数组中粘贴多个字符串,并在它们之间插入另一个字符串。如果数组中只有一个值,则不会显示项目之间的字符串。

因此,您可以从创建数组开始。然后,如果元有值,将这些值放入数组中implode() 他们与and 作为字符串。您还可以检查数组是否为空,如果为空,则完全避免输出:

$giving_back = array();

$givingback_details_funds = get_post_meta( $post->ID,\'givingback_details_funds\', true );

if ( $givingback_details_funds ) {
    $giving_back[] = $givingback_details_funds;
}

$givingback_details_days = get_post_meta( $post->ID, \'givingback_details_days\', true );

if ( $givingback_details_days ) {
    $giving_back[] = _n( \'one working day\', $givingback_details_days. \' working days\', $givingback_details_days );
}

if ( ! empty( $giving_back ) ) {
    echo \'the team donated\' . implode( \' and \', $giving_back );
}
还请注意,我使用了WordPress函数_n() 根据是否$givingback_details_days 是否大于1。

结束

相关推荐