首页 > 解决方案 > 检查订单是否包含具有特定属性值 Woocommerce 的产品

问题描述

我要去检查添加到购物车并购买的产品是否在订单中。即当用户购买可变产品以及其他可变产品时,我想检查是否添加和购买了特定的可变产品。这样我就可以在感谢页面和发送给管理员和客户的电子邮件上动态显示一些信息。

我曾尝试使用检查购物车项目(产品变体)中是否使用了特定属性值答案代码,但是一旦购买了产品,这在Thankyou页面上不起作用

我正在尝试的是,如果订单中的产品具有“自定义”属性值,则显示动态内容,并且如果订单中的产品具有属性值“订单”,则在订单表中显示一个附加表行",使用以下代码:

function add_custom_row_to_order_table( $total_rows, $myorder_obj  ) {
     if ( is_attr_in_cart('custom') ) {
            $cmeasuement = __( 'Yes', 'domain' );
      }else{
            $cmeasuement = __( 'No', 'domain' );
     }

    $total_rows['el_custom'] = array(
       'label' => __('Custom Required?', 'domain'),
       'value'   => $cmeasuement,
    );

    return $total_rows;
}
add_filter( 'woocommerce_get_order_item_totals', 'add_custom_row_to_order_table', 10, 2 );

但我一直得到“否” (见下面的截图),原因是该is_attr_in_cart('custom')函数没有检测属性是否在顺序中。帮助正确的方向让它检测订单是否有具有特定属性值的产品。

在此处输入图像描述

任何帮助表示赞赏。

标签: phpwordpresswoocommerceorderstaxonomy-terms

解决方案


要使其与 WooCommerce订单一起使用,您需要另一个自定义条件函数(您要定位的产品属性$attribute_valueslug值在哪里) :

function is_attr_in_order( $order, $attribute_value ){
    $found = false; // Initializing

    // Loop though order items
    foreach ( $order->get_items() as $item ){
        // Only for product variations
        if( $item->get_variation_id() > 0 ){
            $product = $item->get_product(); // The WC_Product Object
            $product_id = $item->get_product_id(); // Product ID

            // Loop through product attributes set in the variation
            foreach( $product->get_attributes() as $taxonomy => $term_slug ){
                // comparing attribute parameter value with current attribute value
                if ( $attribute_value === $term_slug ) {
                    $found = true;
                    break;
                }
            }
        }
        if($found) break;
    }

    return $found;
}

现在,此条件函数将在您的订单接收页面(thankyou)上的代码中运行,如果找到产品属性,则在总表中添加一个附加行,如果找到产品属性,则使用“是”,如果没有,则添加“否”:

add_filter( 'woocommerce_get_order_item_totals', 'add_custom_row_to_order_table', 10, 3 );
function add_custom_row_to_order_table( $total_rows, $order, $tax_display  ) {
    $domain    = 'woocommerce'; // The text domain (for translations)
    $term_slug = 'custom'; // <==  The targeted product attribute slug value

    $total_rows['custom'] = array(
       'label' => __( "Custom Required?", $domain ),
       'value'   => is_attr_in_order( $order, $term_slug ) ? __( "Yes", $domain ) : __( "No", $domain ),
    );

    return $total_rows;
}

代码在您的活动子主题(或活动主题)的 functions.php 文件中。测试和工作。


如果您只需要定位收到的订单页面,您将在挂钩函数中使用此条件:

if( is_wc_endpoint_url('order-received') ) {
    // The code comes here
}
return $total_rows; // The final filter return outside

推荐阅读