【问题标题】:WooCommerce: Check if product has a specific attributeWooCommerce:检查产品是否具有特定属性
【发布时间】:2020-06-17 01:08:59
【问题描述】:

我想检查产品是否具有特定属性。但有可能该属性只是其中的一个。

例如,产品具有属性语言pa_sprog,并且它具有多种语言。 但我想检查它是否包含“英语”语言。

我发现了这个很棒的代码 (https://stackoverflow.com/a/60295332/1788961):

// for debug purposes, place in comment tags or delete this code
    $product_attributes = $product->get_attributes();
    echo '<pre>', print_r($product_attributes, 1), '</pre>';

    // Get the product attribute value
    $sprog = $product->get_attribute('pa_sprog');

    // if product has attribute 'sprog' value(s)
    if( $sprog == "english" ) {
        echo '<div class="">yes!</div>';
    } else {
        echo '<div class="">no!</div>';
    }

但代码只有在语言“english”是该属性的唯一值时才有效。 如果有多个,则代码不再起作用。

我尝试更改 if 语句以检查语言是否在属性数组中:

if( in_array( "english", $sprog) ) {

但它不起作用。

还有其他方法吗?

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    不是array,而是string,所以你可以使用strpos

    global $product;
    
    // for debug purposes, place in comment tags or delete this code
    $product_attributes = $product->get_attributes();
    echo '<pre>', print_r($product_attributes, 1), '</pre>';
    
    // Get the product attribute value
    $sprog = $product->get_attribute('pa_sprog');
    
    // Gettype - Returns the type of the PHP variable var.
    echo gettype($sprog) . '<br>';
    
    // Result
    echo $sprog . '<br>';
    
    // If product has attribute 'sprog' value(s)
    if( strpos($sprog, 'english') !== false ) {
        echo '<div class="">yes!</div>';
    } else {
        echo '<div class="">no!</div>';
    }
    

    相关:WooCommerce: check if product has attribute

    【讨论】:

      猜你喜欢
      • 2020-06-03
      • 2018-09-17
      • 1970-01-01
      • 1970-01-01
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多