Reputation: 37
I'm trying to add the product category to the below (working) code but I'm not sure how to go about it.
I've tried using product_cat
but as I'm not that experienced with php, I'm just guessing how to achieve this.
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;
}
Upvotes: 1
Views: 936
Reputation: 29614
Following code will also display the product categories on the WooCommerce checkout page
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 );
Upvotes: 1