如何在Woocommerce中将多个自定义字段传递到购物车?

时间:2019-03-30 15:04:31

标签: php wordpress woocommerce cart checkout

我有将单个自定义字段传递到购物车的代码。通过$ item_data数组可以做到这一点。如何扩展数组以添加其他项?例如enrolmentId?

代码如下:

function display_enrolment_text_cart( $item_data, $cart_item ) {
    if ( empty( $cart_item['enrolmentName'] ) ) {
        return $item_data;
    }

    $item_data[] = array(
        'key'     => __( 'Enrolment', 'test' ),
        'value'   => wc_clean( $cart_item['enrolmentName'] ),
        'display' => '',
    );

        // add another item to the $item_data[] array

    return $item_data;
}

add_filter( 'woocommerce_get_item_data', 'display_enrolment_text_cart', 10, 2 );

1 个答案:

答案 0 :(得分:1)

您使用的代码未将任何商品传递给购物车,仅显示了现有的自定义购物车商品数据。

要从其他产品字段或其他相关内容中添加自定义购物车数据,您将使用类似(例如,在单个产品页面上需要一些其他字段)

add_filter( 'woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 10, 3 ); 
function add_custom_cart_item_data($cart_item_data, $product_id, $variation_id ){
    if( isset( $_POST['product_field1'] ) ) {
        $cart_item_data['custom_data'][1] = sanitize_text_field( $_POST['product_field1'] );
    }
    if( isset( $_POST['product_field2'] ) ) {
        $cart_item_data['custom_data'][2] = sanitize_text_field( $_POST['product_field2'] );
    }
    return $cart_item_data;
}

现在在购物车和结帐页面中显示该自定义购物车项目数据:

add_filter( 'woocommerce_get_item_data', 'display_enrolment_text_cart', 10, 2 );
function display_enrolment_text_cart( $item_data, $cart_item ) {
    if ( isset($cart_item['enrolmentName']) && ! empty($cart_item['enrolmentName']) ) {
        $item_data[] = array(
            'key'     => __( 'Enrolment', 'test' ),
            'value'   => wc_clean( $cart_item['enrolmentName'] ),
            'display' => '',
        );
    }

    // Additional displayed custom cat item data
    if ( isset($cart_item['custom_data'][1]) && ! empty($cart_item['custom_data'][1])  ) {
        $item_data[] = array(
            'key'     => __( 'Field 1', 'test' ),
            'value'   => wc_clean( $cart_item['custom_data'][1] ),
            'display' => '',
        );
    }

    if ( isset($cart_item['custom_data'][2]) && ! empty($cart_item['custom_data'][2])  ) {
        $item_data[] = array(
            'key'     => __( 'Field 2', 'test' ),
            'value'   => wc_clean( $cart_item['custom_data'][2] ),
            'display' => '',
        );
    }
    return $item_data;
}

代码进入您的活动子主题(或活动主题)的function.php文件中。应该可以。

相关主题: Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

相关的完整线程: Add custom field in products to display in cart, checkout and in orders