wordpress - 在 WooCommerce 结帐页面上显示产品类别
问题描述
我正在尝试将产品类别添加到以下(工作)代码中,但我不确定如何去做。
我尝试过使用product_cat
,但由于我对 php 没有那么丰富的经验,我只是在猜测如何实现这一点。
add_filter( 'woocommerce_get_item_data', 'display_custom_product_field_data', 10, 2 );
function display_custom_product_field_data( $cart_data, $cart_item ) {
$meta_keys = array('time','date');
$dictionary = array('time'=>'Time:','date'=>'Date:' );
$product_id = $cart_item['product_id'];
foreach($meta_keys as $key=>$meta_key){
$meta_value = get_post_meta( $product_id, $meta_key, true );
if( !empty( $cart_data ) ) $custom_items = $cart_data;
if( !empty($meta_value) ) {
$custom_items[] = array(
'key' => __( $dictionary[$meta_key] , 'woocommerce'), //or user $meta_key
'value' => $meta_value,
'display' => $meta_value,
);
}
}
return $custom_items;
}
解决方案
以下代码还将在 WooCommerce 结帐页面上显示产品类别
function display_custom_product_field_data( $cart_item_data, $cart_item ) {
// Product ID
$product_id = $cart_item['product_id'];
// Get post meta
$time = get_post_meta( $product_id, 'time', true );
// NOT empty
if( ! empty( $time ) ) {
$cart_item_data[] = array(
'key' => __( 'Time', 'woocommerce'),
'value' => $time,
);
}
// Get terms
$term_names = wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'names' ) );
if( ! empty( $term_names ) ) {
$cart_item_data[] = array(
'key' => __( 'Categories', 'woocommerce'),
'value' => implode( ", ", $term_names )
);
}
// Get post meta
$date = get_post_meta( $product_id, 'date', true );
// NOT empty
if( ! empty( $date ) ) {
$cart_item_data[] = array(
'key' => __( 'Date', 'woocommerce'),
'value' => $date,
);
}
return $cart_item_data;
}
add_filter( 'woocommerce_get_item_data', 'display_custom_product_field_data', 10, 2 );
推荐阅读
- r - 如何在 R 的 for 循环中保存更改名称的数据帧?
- django - Django H14 Heroku 错误,我该如何解决?
- javascript - 如何最好地在烧瓶应用程序中动态填充下拉列表?
- json - 修改 json 对象数组
- powershell - 使用employeeid更新员工经理
- python - 在烧瓶中创建可下载文件的问题
- swiftui - 防止 SwiftUI App 进入睡眠操作 WatchOS
- javascript - 谷歌注册不适用于第一次点击元素,但之后工作正常。为什么?
- apache-spark - 为什么一旦我将“mapValues()”应用于 RDD,属性就会消失?
- sql - SQL中多个表中的项目总和