2012-10-04 14 views
0

我需要一個WordPress的循環,爲每個職位檢查一個元數值變量以前分配給每個分類的職位,並返回這些元變量的總和。 爲此,我認爲我需要一個動態變量名稱。我的意思是這樣的:每個WordPress的帖子都有不同的動態變量:如何在循環中聲明?

variablerelatedtopost = metataxonomy1 + metataxonomy2 + ... + metataxonomyn
回聲variablerelatedtopost

我怎麼能這樣做?是否有可能通過循環生成一個動態數字變量?以及如何以一般方式提及它,而不用它的名字來表達它?
謝謝大家!對於可能的英文錯誤感到抱歉:P

編輯:我剛剛意識到Alex的代碼並不是我想要的。我需要一個變量,在每個帖子中更改名稱,哪個值始終爲0.是否有解決方案?

回答

0

你能不能像這樣給你的循環添加一個計數器?

//Total should start @ 0 before the loop 
$total = 0; 

// The Query 
$the_query = new WP_Query($args); 

// The Loop 
while ($the_query->have_posts()) : $the_query->the_post(); 
$amount = get_post_meta($post->ID, 'the_meta_data_field', true); 
$total = $total + $amount; 
endwhile; 

//echo total 
echo $total; 
+0

我用一點點的改變,你的解決方案: '而($ the_query-> have_posts ()):$ the_query-> the_post(); $ amount = get_post_meta($ post-> ID,'the_meta_data_field',true); $ total = $ amount + $ variablerelatedtotaxonomy; echo $ total; endwhile;' ,因爲我需要每個帖子的總數不同(每篇文章只計算帖子的與分類相關的變量),但該原則起作用!非常感謝你! –

+0

對不起,我犯了一個錯誤:我剛剛意識到代碼不是我想要的。我需要一個變量在每個帖子中更改名稱,哪個值始終爲0,所以這不是正確的解決方案。我錯誤地發佈了答案,在一個只有一個分類變量的函數中檢查它(它是這樣工作的,有兩個變量顯然不起作用)。 –

0

我發現了我的問題的解決方案:一個數組,它增加了它在每個循環中的長度。我知道這很簡單,但因爲我只是一個初學者,所以花了我一些時間思考它。我在這裏發佈的代碼,所以也許這可以幫助別人(如果你發現錯誤或有改進,請告訴我)

//Before the loop, empty array 
$totale = array(); 

// WP Loop 
while ($loop->have_posts()) : $loop->the_post(); 

$totale[] = 0; 
$indice = (count($totale)) - 1; 

// $termvariable was previously set up as a term meta value 
if(has_term('numberofterm', 'nameoftaxonomy')) { 
$totale[$indice] = $termvariable + $totale[$indice]; 
}