2014-10-16 91 views
0

我幾乎沒有PHP知識,但我需要做一些鍛鍊。如果有這些陳述,我會在列表中找到產品的可用(交易或當前)價格。WordPress的:IF聲明結果和作爲變量使用

<?php 
$currentPrice = get_field('incentive_current_price'); 
$oldPrice = get_field('incentive_old_price'); 

if (($currentPrice != null) && ($oldPrice != null)) { 
    the_field('incentive_current_price'); 
} 
elseif (($currentPrice == null) && ($oldPrice != null)) { 
    the_field('incentive_old_price'); 
} 
elseif (($currentPrice != null) && ($oldPrice == null)) { 
    the_field('incentive_current_price'); 
} 
else { 
} 
?> 

這工作正常。我還有另外一個領域,我需要從這個列表中顯示價格最低的產品。我用這個是:

$connected = new WP_Query(array(
'connected_type' => 'incentives_to_products', 
'connected_items' => get_queried_object(), 
'nopaging' => true, 
'meta_key'  => 'incentive_old_price', 
'orderby'  => 'meta_value_num', 
'order'   => 'DESC')); 

問題是有時我有current_prices,這只是忽略它orderby old_price。有沒有辦法將if語句保存爲變量並在meta_key部分中使用。或者你有其他方法來實現這一目標嗎?

感謝您提前

回答

0

很簡單,保存爲一個變量。

如果你想使用它的代碼在範圍內,你可以在if語句中創建你的變量。

看起來像the_field()直接回聲,所以你要麼必須找到一個返回而不是回聲的相應函數,要麼使用輸出緩衝來保存結果到一個變量。

後者:

if (($currentPrice != null) && ($oldPrice != null)) { 
    the_field('incentive_current_price'); 
    ob_start(); 
     the_field('incentive_current_price'); 
     $my_price = ob_get_contents; 
    ob_end_clean(); 
} 
elseif (($currentPrice == null) && ($oldPrice != null)) { 
    ob_start(); 
     the_field('incentive_old_price'); 
     $my_price = ob_get_contents; 
    ob_end_clean(); 
} 
elseif (($currentPrice != null) && ($oldPrice == null)) { 
    ob_start(); 
     the_field('incentive_current_price'); 
     $my_price = ob_get_contents; 
    ob_end_clean(); 
} 
else { 
$my_price = 'default_value'; 
} 

如果你需要使用它的範圍,你可以聲明它作爲一個全球性的,這將是隨處可在您的腳本。

global $my_price; 

然後,當你想使用它

global $my_price; 
echo $my_price; 
+0

非常感謝您對明確的答案。 是的,the_field()直接回聲,如果我使用get_field()它不。 – archglg 2014-10-16 11:45:12

+0

不用擔心,它幫助:) – 2014-10-16 11:48:41