什么是在变量中存储post_meta值的最有效和最简单的方法,以及meta_key不存在时的默认值?
我想使用这样的东西,meta_value将始终是一个数字:
public class SUIComboBox : UIComboBox
{
/// <summary>
/// The prevously selected value
/// </summary>
private object _PreviousSelectedValue = null;
public event EventHandler<EventArgs> SelectedValueChanging;
protected virtual void OnSelectedValueChanging(object sender, CancelEventArgs e)
{
var handler = SelectedValueChanging;
handler?.Invoke(sender, e);
}
}
public class SelectedValueChangingEventArgs : CancelEventArgs
{
}
但这引发了一个PHP错误:
致命错误:无法对表达式的结果使用isset()
在我的脑海中,我唯一能想到的东西是:
$bv_faq_thumbs_up = isset(get_post_meta($post->ID, '_bv_faq_thumbs_up', true)) ? get_post_meta($post->ID, '_bv_faq_thumbs_up', true) : 0;
但这似乎是啰嗦和臃肿,这是正确的方法(在速度,效率和整洁方面)
答案 0 :(得分:1)
试试这段代码;
$bv_faq_thumbs_up = get_post_meta($post->ID, '_bv_faq_thumbs_up', true);
if(empty($bv_faq_thumbs_up)) {
$bv_faq_thumbs_up = 0;
}
OR
$bv_faq_thumbs_up = get_post_meta($post->ID, '_bv_faq_thumbs_up', true);
$bv_faq_thumbs_up = (!empty($bv_faq_thumbs_up)) ? $bv_faq_thumbs_up : 0;
OR
if(metadata_exists( 'post', $post->ID, '_bv_faq_thumbs_up' ) === null) {
$bv_faq_thumbs_up = 0;
} else {
$bv_faq_thumbs_up = get_post_meta($post->ID, '_bv_faq_thumbs_up', true);
}
面向未来用户
答案 1 :(得分:0)
根据Stender的评论,我发现使用metadata_exists
代替isset
允许相同的想法工作,仍然包含在一个句子中,并且只使用get_post_meta()
函数一次,同时设置默认值。
$bv_faq_thumbs_up = metadata_exists('post', $post->ID, '_bv_faq_thumbs_up') ? get_post_meta($post->ID, '_bv_faq_thumbs_up', true) : 0;