php自定义字段和页面,php – 保存产品自定义字段并将其显示在购物车页面中

您的代码中存在大量错误和缺失的内容

1)设置:

If you want to display correctly the label “Name On T-Shirt” on customer Orders and email notifications, you need to create an attribute for this label name (under Products > Attributes):

创建产品属性:

8074d03e2f777db7ab9ba258e72542fc.png

为此属性添加一些值:

f944ee743b4f77a14edaff7b73f47c20.png

和……

7c1533d1f6c7c694b1157c1bba26e8f6.png

然后保存…

2)守则:

// Add the custom field to product pages

add_action( 'woocommerce_before_add_to_cart_button', 'add_nmy_custom_product_field', 10, 0 );

function add_nmy_custom_product_field() {

?>

}

// Save the custom product field data in Cart item

add_action( 'woocommerce_add_cart_item_data', 'save_in_cart_my_custom_product_field', 10, 2 );

function save_in_cart_my_custom_product_field( $cart_item_data, $product_id ) {

if( isset( $_POST['name-on-tshirt'] ) ) {

$cart_item_data[ 'name-on-tshirt' ] = $_POST['name-on-tshirt'];

// When add to cart action make an unique line item

$cart_item_data['unique_key'] = md5( microtime().rand() );

WC()->session->set( 'custom_data', $_POST['name-on-tshirt'] );

}

return $cart_item_data;

}

// Render the custom product field in cart and checkout

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

function render_custom_field_meta_on_cart_and_checkout( $cart_data, $cart_item ) {

$custom_items = array();

if( !empty( $cart_data ) )

$custom_items = $cart_data;

if( $custom_field_value = $cart_item['name-on-tshirt'] )

$custom_items[] = array(

'name' => __( 'Name On T-Shirt', 'woocommerce' ),

'value' => $custom_field_value,

'display' => $custom_field_value,

);

return $custom_items;

}

// Add the the custom product field as item meta data in the order

add_action( 'woocommerce_add_order_item_meta', 'tshirt_order_meta_handler', 10, 3 );

function tshirt_order_meta_handler( $item_id, $cart_item, $cart_item_key ) {

$custom_field_value = $cart_item['name-on-tshirt'];

if( ! empty($custom_field_value) )

wc_update_order_item_meta( $item_id, 'pa_name-on-tshirt', $custom_field_value );

}

此代码位于活动子主题(或主题)的function.php文件中,或者也可以放在任何插件文件中.

此代码适用于WooCommerce版本,测试范围为2.5到3.0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值