【问题标题】:Wordpress if custom field value is null previous posts' value is displayed如果自定义字段值为空,则显示 Wordpress 以前的帖子的值
【发布时间】:2013-08-20 09:55:11
【问题描述】:

我的这段代码带有一个循环,给我带来了一些麻烦和奇怪的结果。 这个特定的帖子类型有一些自定义字段,我将它们放在一个数组中。一切都按预期工作,但如果一个字段没有值,它将从循环中的上一篇文章中获取值。

假设我在 Wordpress 中有这些帖子:

Post ID 10
custom_1 = 10
custom_2 = 20
custom_3 = 30

Post ID 20
custom_1 = 40
custom_2 = null
custom_3 = null

如果我运行我的循环,我会得到这些结果

Post ID 10
custom_1 = 10
custom_2 = 20
custom_3 = 30

Post ID 20
custom_1 = 40
custom_2 = 20 (instead of null)
custom_3 = 30 (instead of null)

这是该循环的简短版本:

$query = new WP_Query($query_arg);
if ($query->have_posts()) {
while ($query->have_posts()) {
    $query->the_post();
    $result[] = array(  
    "custom_1" => get_post_meta($post->ID, 'custom_1', true),
    "custom_2" => get_post_meta($post->ID, 'custom_2', true),
    "custom_3" => get_post_meta($post->ID, 'custom_3', true)
        );
      }
}
wp_reset_postdata();

我似乎无法理解这个..几乎尝试了所有方法,但没有任何接缝可以工作。

有人知道这里发生了什么吗?

更新: 通过将循环更改为此来修复它。

$query = new WP_Query($query_arg);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();

//set vars to "" which 'resets' the value with every new post in the loop
$custom_1 = "";
$custom_2 = "";
$custom_3 = "";

//set vars to the value of the custom fields
$custom_1 => get_post_meta($post->ID, 'custom_1', true);
$custom_2 => get_post_meta($post->ID, 'custom_2', true);
$custom_3 => get_post_meta($post->ID, 'custom_3', true);

$result[] = array( 
"custom_1" => $custom_1,
"custom_2" => $custom_2,
"custom_3" => $custom_3
    );
  }
}
wp_reset_postdata();

【问题讨论】:

    标签: custom-fields wordpress


    【解决方案1】:

    这可能是由于 MYSQL 处理 null 的方式。 Null 表示没有值,因此它们在数据库中没有空间,甚至没有空空间。但是,数据库中确实会显示一个空字符串。

    试试下面的

    Post ID 10
    custom_1 = 10
    custom_2 = 20
    custom_3 = 30
    
    Post ID 20
    custom_1 = 40
    custom_2 = ""
    custom_3 = ""
    

    【讨论】:

    • 感谢 eevaa,虽然不是很好的解决方案,但确实为我指明了正确的方向。
    猜你喜欢
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 2014-08-02
    • 2014-07-31
    • 2013-03-09
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    相关资源
    最近更新 更多