在WooCommerce结帐页面上显示产品类别

时间:2020-06-14 08:07:11

标签: wordpress woocommerce categories product checkout

我正在尝试将产品类别添加到下面的(有效)代码中,但是我不确定该怎么做。

我尝试使用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;
}

1 个答案:

答案 0 :(得分:1)

以下代码还将在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 );