问题描述
我有一些用户提交的变量,希望在我的网站的其他部分显示,如下所示:
I have some user-submitted variables that I want to display in a different part of my site like this:
<div class="pre_box">Term: </div>
<div class="entry"><?php $key='term'; echo get_post_meta($post->ID, $key, true); ?></div>
有时,这些变量可能为空,在这种情况下,我不想显示空变量的标签.在上面的示例中,我想隐藏<div class="pre_box">Term: </div>
部分.有什么简单的方法可以检查上面的php变量是否为空,并防止标签显示?
Occasionally, these variables might be empty in which case I don't want to display the label for the empty variable. In the example above I would want to hide the <div class="pre_box">Term: </div>
part. Is there some simple way to check if a php variable like the one above is empty and prevent the label from being displayed?
更新,这是使用!empty
Update, here is the code using !empty
<?php $key='term' ?>
<?php if( !empty( $key ) ): ?>
<div class="pre_box">Term: </div>
<div class="entry">
<?php echo get_post_meta($post->ID, $key, true); ?>
</div>
<?php endif; ?>
但是,无论如何,它仍然显示内容.我认为问题可能出在我定义$ key变量的方式上.我试图从wordpress post中设置的自定义字段中提取数据,这就是$ post-> ID业务的全部内容.
However, this still displays the content no matter what. I think the problem might be in the way I am defining the $key variable. Im trying to pull data from a custom field set in a wordpress post - thats what the $post->ID business is all about.
推荐答案
<?php
$post_meta = get_post_meta($post->ID, 'term', true);
if (!empty($post_meta)) {
?>
<div class="pre_box">Term: </div>
<div class="entry"><?php echo $post_meta; ?></div>
<?php
}
?>
这篇关于检查变量是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!