【问题标题】:If attribute value equals to... show something如果属性值等于... 显示一些东西
【发布时间】:2020-07-21 16:23:35
【问题描述】:

我正在做一些关于 wordpress + woocommerce 的工作。 我为某些产品输入了一些“过滤器”属性值。

因此,如果此产品的属性值包含“木纹”值,我想在前端回显 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

【问题讨论】:

    标签: php wordpress attributes


    【解决方案1】:

    如果这返回所述产品的术语数组:

    $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
    }
    

    【讨论】:

    • 对不起,所以.. 我试过了,但我不确定出了什么问题。你写的一个衬里,是要替换我最初在上面写的整个代码?我对么?像这样的东西? if (in_array("Wood Grains", get_the_terms($product->id, 'pa_filter'))) { echo "Have a good day!"; }
    • 我已经更新了关于一个班轮的帖子。是的;这就是你使用它的方式。你试过了吗?
    • 是的,我已经尝试过使用更新的单线。但不幸的是,它没有回应任何东西。我会尝试弄乱代码,看看是否有任何结果。谢谢
    • 好吧,忽略单行。这样做$terms = get_the_terms( $product->id, 'pa_filter'); 然后像我展示的那样检查。如果它仍然不起作用,你能var_dump($terms); - 我想看看它的内容。
    • 对你的“做这个......”不太了解,反正做了一个 var 转储。这是输出array(1) { [20]=> object(stdClass)#277 (11) { ["term_id"]=> int(20) ["name"]=> string(11) "Wood Grains" ["slug"]=> string(11) "wood-grains" ["term_group"]=> int(0) ["term_taxonomy_id"]=> int(21) ["taxonomy"]=> string(9) "pa_filter" ["description"]=> string(0) "" ["parent"]=> int(0) ["count"]=> int(1) ["object_id"]=> int(13) ["filter"]=> string(3) "raw" } }
    【解决方案2】:

    我找到了解决问题的更好方法。我的 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">';
         }
        }
    ?>
    

    请注意术语名称区分大小写。

    【讨论】:

      【解决方案3】:

      foreach 打印警告:为 foreach() 提供的参数无效...

      这“纯粹”对我有用:

      if ( is_product() && has_term( 'Wood Grains', 'pa_filter' )) {
          echo '<img src="Texture.jpg">';
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-09
        • 1970-01-01
        • 1970-01-01
        • 2013-01-09
        • 1970-01-01
        相关资源
        最近更新 更多