在 WooCommerce 的购物车和结账页面上显示购买备注和属性

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

以下代码有效,并将购买备注添加到购物车项目中。

add_filter( 'woocommerce_get_item_data', 'wc_test', 10, 2 );  
function wc_test ( $other_data, $cart_item ){
    $post_data = get_post( $cart_item['product_id'] );
    $other_data[] = array( 'name' =>  $post_data->_purchase_note );
    return $other_data;
}

但是,对于没有注释的产品,我总是得到“:”结果。

我还需要在注释下添加特定属性。

有什么建议吗?

php wordpress woocommerce cart checkout
1个回答
4
投票
  • 冒号会自动添加到键中。因为您只使用名称,所以这将添加在最后。
  • 您可以使用 get_purchase_note()

所以你得到:

// Display on cart & checkout pages
function filter_woocommerce_get_item_data( $item_data, $cart_item ) {
    // Get an instance of the WC_Product object
    $product = $cart_item['data'];
    
    // Get purchase_note
    $purchase_note = $product->get_purchase_note();
    
    // Get the product attribute value (adjust if desired)
    $attribute = $product->get_attribute( 'pa_color' );
    
    // When empty
    if ( empty ( $attribute ) ) {
        $attribute = '';
    }
    
    // NOT empty
    if ( ! empty( $purchase_note ) ) {
        $item_data[] = array(
            'key'     => __( 'Note', 'woocommerce' ),
            'value'   => $purchase_note . $attribute,
            'display' => $purchase_note . $attribute,
        );
    }
    
    return $item_data;
}
add_filter( 'woocommerce_get_item_data', 'filter_woocommerce_get_item_data', 10, 2 );
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.