2013-08-20 51 views
0

我有這樣的代碼,給我一些麻煩和奇怪的結果。 這個特定的帖子類型有一些我放在數組中的自定義字段。一切都按預期工作,但如果一個字段沒有任何價值,它會從循環中的上一篇文章中獲取值。Wordpress如果自定義字段值爲null以前的帖子的值顯示

比方說,我在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(); 

回答

0

這可能是由於MySQL處理。 Null意味着沒有值,所以它們在數據庫中沒有空間,甚至沒有空間。然而,一個空字符串顯示在數據庫中。

請嘗試以下

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

Post ID 20 
custom_1 = 40 
custom_2 = "" 
custom_3 = "" 
+0

感謝eevaa,不太解決方案,但沒有點我到正確的方向。 – Kwint

相關問題