在WooCommerce的结账页面上显示产品类别。

问题描述 投票:0回答:1

我试图将产品类别添加到下面(工作)的代码中,但我不知道如何去做。

我试过使用 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;
}
wordpress woocommerce categories product checkout
1个回答
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', ['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 );
© www.soinside.com 2019 - 2024. All rights reserved.