![](/img/trans.png)
[英]Add to cart with data from a URL (post) using the GET method in Woocommerce
[英]Add to cart with custom data from an url using GET method in Woocommerce 3
在 Woocommerce 中,我使用來自 URL 的 GET 方法將產品添加到購物車,例如:
http://example.com/cart/?add-to-cart=10
現在我希望能夠同時添加一些自定義數據作為產品說明,例如:
http://example.com/cart/?add-to-cart=10¬e=hinote
然后將該“hinote”值保存為購物車項目數據。 放置訂單后,我想將“hinote”保存在訂單商品數據中,並將其顯示為自定義訂單商品數據。
那可能嗎?
任何幫助表示贊賞。
是的,這是可能的,而且很簡單……試試下面的代碼:
// Add custom note as custom cart item data
add_filter( 'woocommerce_add_cart_item_data', 'get_custom_product_note', 30, 2 );
function get_custom_product_note( $cart_item_data, $product_id ){
if ( isset($_GET['note']) && ! empty($_GET['note']) ) {
$cart_item_data['custom_note'] = sanitize_text_field( $_GET['note'] );
$cart_item_data['unique_key'] = md5( microtime().rand() );
}
return $cart_item_data;
}
// Display note in cart and checkout pages as cart item data - Optional
add_filter( 'woocommerce_get_item_data', 'display_custom_item_data', 10, 2 );
function display_custom_item_data( $cart_item_data, $cart_item ) {
if ( isset( $cart_item['custom_note'] ) ){
$cart_item_data[] = array(
'name' => "Note",
'value' => $cart_item['custom_note'],
);
}
return $cart_item_data;
}
// Save and display product note in orders and email notifications (everywhere)
add_action( 'woocommerce_checkout_create_order_line_item', 'add_custom_note_order_item_meta', 20, 4 );
function add_custom_note_order_item_meta( $item, $cart_item_key, $values, $order ) {
if ( isset( $values['custom_note'] ) ){
$item->update_meta_data( 'Note', $values['custom_note'] );
}
}
代碼位於活動子主題(或活動主題)的 function.php 文件中。 測試和工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.