我正在尝试将产品类别添加到下面的(有效)代码中,但不确定如何去做。
我曾尝试使用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;
}
以下代码还将显示类别
function display_custom_product_field_data( $cart_data, $cart_item ) {
$meta_keys = array( 'time', 'date' );
$dictionary = array( 'time' => 'Time:', 'date' => 'Date:' );
// Product ID
$product_id = $cart_item['product_id'];
// Get terms
$term_names = wp_get_post_terms( $product_id, 'product_cat', ['fields' => 'names'] );
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;
$meta_value = 'abc';
if( ! empty( $meta_value ) ) {
$custom_items[] = array(
'key' => __( $dictionary[$meta_key] , 'woocommerce'), //or user $meta_key
'value' => $meta_value,
'display' => $meta_value,
);
}
}
if( ! empty( $term_names ) ) {
$custom_items[] = array(
'name' => __( 'Categories' , 'woocommerce'), //or user $meta_key
'value' => implode( ", ", $term_names )
);
}
return $custom_items;
}
add_filter( 'woocommerce_get_item_data', 'display_custom_product_field_data', 10, 2 );