php - 检查订单是否包含具有特定属性值 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')
函数没有检测属性是否在顺序中。帮助正确的方向让它检测订单是否有具有特定属性值的产品。
任何帮助表示赞赏。
解决方案
要使其与 WooCommerce订单一起使用,您需要另一个自定义条件函数(您要定位的产品属性$attribute_value
的slug值在哪里) :
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
推荐阅读
- python - 无法计算替换某些符号的两个值
- sql - SQL 更新表中的记录,涉及同一表中的另一条记录
- c# - WPF
似乎无法识别并导致错误 - microsoft-teams - 以编程方式在 MSTeams 中创建选项卡
- c++ - 对 unique_lock 和 scoped_lock 使用相同的互斥锁
- reactjs - 如何使用 Preact 和 TypeScript 对子组件进行类型检查?
- sails.js - 安排脚本每隔一段时间运行一次
- ios - UIButton Array - 每个按钮都指向 CollectionView swift 中的标记 0
- android - 片段没有宽度和高度
- javascript - 使用文本节点将 JSON 数据呈现到准备好的 HTML 页面中