woocommerce_thankyou钩子触发后拼接产品名与属性及解决波斯语兼容问题
WooCommerce thankyou钩子产品名称与变体属性拼接实现
需求说明
需要在woocommerce_thankyou钩子触发后,实现订单内产品名称与其对应变体属性名称的拼接输出。
原有代码及存在的问题
原有代码
$order_items = $order->get_items(); foreach ($order_items as $item_key => $item) { $product = $item->get_product(); // Get the WC_Product Object if( $product->is_type( 'variation' ) ){ $attributes = $product->get_attributes(); $variation_names = array(); if( $attributes ){ foreach ( $attributes as $key => $value) { $variation_key = end(explode('-', $key)); $variation_names[] = ucfirst($variation_key) .' : '. $value; } } echo implode( '<br>', $variation_names ); } }
存在问题
原有代码直接读取属性值输出,多语言兼容差,波斯语输出时会出现编码乱码:
%da%86%d8%b1%d8%a8%db%8c
期望输出格式
"product Name , color:red, size:85"
修复后可用方案
通过调用WooCommerce原生方法获取属性标签和属性值的可读名称,完美解决多语言编码兼容问题:
//اضافه کردن نام ویژگی به اسم محصول //Add attribute label name to product name if( $product->is_type( 'variation' ) ){ $s =''; $s1 = ''; foreach ($product->get_attributes() as $taxonomy => $attribute_obj ) { // Get the attribute label $attribute_label_name = wc_attribute_label($taxonomy); //convert to array $attribute_arr = json_decode(json_encode($attribute_obj),true); $term_name = get_term_by( 'slug', $attribute_arr, $taxonomy)->name; $s = $s . $s1 .$attribute_label_name.':'.$term_name; $s1 = ', '; } $name = $name . '(' .$s. ')'; echo '<p>' . $name. '</p>'; }
内容的提问来源于stack exchange,提问作者mmd
相关产品推荐
相关产品推荐

