So erhalten Sie Produktvarianten-Attribut-Slugs aus dem Woocommerce-Warenkorbartikel
P粉895187266
P粉895187266 2024-02-04 10:19:26
0
1
367

Ich muss im Warenkorb nachsehen, ob einem Produkt ein bestimmtes Produktattribut hinzugefügt wurde. (Dies geschieht innerhalb einer benutzerdefinierten Versandfunktion, die in woocommerce_package_rates eingebunden ist.)

Ich habe die Varianten-ID für jeden Artikel in meinem Warenkorb, weiß aber nicht, wie ich den Varianten-Slug für diesen Artikel bekomme...

foreach (WC()->cart->get_cart() as $cart_item) {

    // $product_in_cart = $cart_item['product_id'];
    
    $variation_id = $cart_item['variation_id'] > 0 ? $cart_item['variation_id'] : 
    $cart_item['product_id'];
    
    $variation = wc_get_product($variation_id);

    $variation_name = $variation->get_formatted_name(); //I want to get the slug instead.

    // if there is the swatch variation of any product in the cart.
    if (  $variation_name == 'swatch') $cart_has_swatch = "true"; 
    
}

P粉895187266
P粉895187266

Antworte allen(1)
P粉600402085

你造成了一些混乱。在 WooCommerce 购物车项目上:

  • 产品变体对象始终为 $cart_item['data']
  • 可以通过 $cart_item['variation'] 访问变体属性(这是产品属性分类法、产品属性 slug 值对的数组)
  • $variation->get_formatted_name() 是产品变体名称(已格式化),因此不是变体产品属性。
  • 使用 woocommerce_package_rates 过滤器挂钩,使用 $package['contents'] 而不是 WC()->cart->get_cart()

您的问题不是很清楚,因为我们不知道您是否在属性分类法或属性段值中搜索术语“样本”。

尝试以下操作:

add_filter( 'woocommerce_package_rates', 'filtering_woocommerce_package_rates', 10, 2 );
function filtering_woocommerce_package_rates( $rates, $package ) {
    $cart_has_swatch = false; // initializing

    // Loop through cart items in this shipping package
    foreach( $package['contents'] as $cart_item ) {
        // Check for product variation attributes
        if( ! empty($cart_item['variation']) ) {
            // Loop through product attributes for this variation
            foreach( $cart_item['variation'] as $attr_tax => $attr_slug ) {
                // Check if the world 'swatch' is found
                if ( strpos($attr_tax, 'swatch') !== false || strpos( strtolower($attr_slug), 'swatch') !== false ) {
                    $cart_has_swatch = true; // 'swatch' found
                    break; // Stop the loop
                }
            }
        }
    }

    if ( $cart_has_swatch ) {
        // Do something
    }


    return $rates;
}

它应该适合你。

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!