2014-04-23 27 views
1

我正在研究wordpress + woocommerce上的內容。 我輸入了一些產品的「過濾器」屬性值。如果屬性值等於...顯示的東西

因此,如果此產品的屬性值包含「Wood Grains」值,我想在前端回顯Woodgrains.jpg。

因此,如果value = Texture,我想回顯Texture.jpg圖標。

下面的代碼是我迄今爲止編寫的代碼,但是這隻能迴應所有標記爲產品的值,我無法弄清楚如何更改以獲取'if'語句。

$terms = get_the_terms($product->id, 'pa_filter'); 
foreach ($terms as $term) { 
echo $term->name; 
} 

這裏是一個什麼樣的代碼在前端上面做了截圖: http://edleuro.com/new/wp-content/themes/mystile/img/1.png

回答

0

我找到了解決我的問題的更好方法。我在我的content-product.php woocommerce模板中有這個。

<?php 
    $terms = get_the_terms($product->id, 'pa_filter'); 
    foreach($terms as $term){ 
    if($term->name == 'Wood Grains'){ 
     echo '<img src="icon_woodgrains.gif">'; 
    } 
    } 
?> 

請注意,術語名稱區分大小寫。

2

如果返回上述乘積項的數組:

$terms = get_the_terms($product->id, 'pa_filter'); 

您可以檢查返回的結果數組有你正在尋找的這樣做:

if (in_array("Wood Grains", $terms)) 
{ 
    // has it 
} 
else 
{ 
    // doesn't have it 
} 

更新根據您的回答我的答案

,我想出了以下內容:

創建一個輔助函數是這樣的:

function termExists($myTerm, $terms) 
{ 
    if (is_array($terms)) { 
     foreach ($terms as $id => $data) { 
      if ($data->name == $myTerm) 
       return true; 
     } 
    } 
    return false; 
} 

然後你像這樣使用它:

if (termExists('Wood Grains', get_the_terms($product->id, 'pa_filter'))) 
{ 
    // term exists 
} 
else 
{ 
    // does not exists 
} 
+0

對不起,所以..我試過,但我不知道什麼是錯的。你寫的一行代碼是替換我最初寫在上面的整個代碼?我對麼? 這樣的事情? 'if(in_array(「Wood Grains」,get_the_terms($ product-> id,'pa_filter'))) { \t echo「祝您有美好的一天! }' – wsgg

+0

我已經更新了我的帖子,關於一個班輪。是;這就是你如何使用它。你試過了嗎? – Latheesan

+0

是的,我已經嘗試過更新的單線。但不幸的是它沒有迴應任何事情。我會嘗試使用代碼來查看是否有任何內容出現。謝謝 – wsgg

相關問題