0

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

假设我在 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();
4

1 回答 1

0

这可能是由于 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 = ""
于 2013-08-20T10:42:12.837 回答