我在主题的 functions.php 中使用以下代码在 woocommerce 单一产品页面上添加了一些自定义选项:
function options_on_single_product(){
?>
<input type="radio" name="option1" checked="checked" value="option1"> option 1 <br />
<input type="radio" name="option1" value="option2"> option 2
<?php
}
add_action("woocommerce_before_add_to_cart_button", "options_on_single_product");
现在我想在购物车页面上显示所选选项的值。请帮我做这件事。 谢谢
最佳答案
以下是将产品自定义字段存储在购物车对象中并在购物车和结帐页面中显示的完整代码:
// Output the Custom field in Product pages
add_action("woocommerce_before_add_to_cart_button", "options_on_single_product", 1);
function options_on_single_product(){
?>
<label for="custom_field">
<input type="radio" name="custom_field" checked="checked" value="option1"> option 1 <br />
<input type="radio" name="custom_field" value="option2"> option 2
</label> <br />
<?php
}
// Stores the custom field value in Cart object
add_filter( 'woocommerce_add_cart_item_data', 'save_custom_product_field_data', 10, 2 );
function save_custom_product_field_data( $cart_item_data, $product_id ) {
if( isset( $_REQUEST['custom_field'] ) ) {
$cart_item_data[ 'custom_field' ] = esc_attr($_REQUEST['custom_field']);
// below statement make sure every add to cart action as unique line item
$cart_item_data['unique_key'] = md5( microtime().rand() );
}
return $cart_item_data;
}
// Outuput custom Item value in Cart and Checkout pages
add_filter( 'woocommerce_get_item_data', 'output_custom_product_field_data', 10, 2 );
function output_custom_product_field_data( $cart_data, $cart_item ) {
if( isset( $cart_item['custom_field'] ) ) {
$cart_data[] = array(
'key' => __('Custom Item', 'woocommerce'),
'value' => $cart_item['custom_field'],
'display' => $cart_item['custom_field'],
);
}
return $cart_data;
}
代码位于您的事件子主题(或主题)的 function.php 文件中或任何插件文件中。
此代码已经过测试并且可以工作。
关于php - 在购物车中保存产品自定义字段值并将其显示在购物车和结帐中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43423161/