Skip to content

Instantly share code, notes, and snippets.

@huanlin
Last active February 18, 2020 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huanlin/fd6902bbaecfc9faf108498e84e1c0e8 to your computer and use it in GitHub Desktop.
Save huanlin/fd6902bbaecfc9faf108498e84e1c0e8 to your computer and use it in GitHub Desktop.
Add Custom Field for WooCommerce Cart
/**
* Add a custom text input field to the product page
* 從 URL 參數取得 referer ID,並顯示於表單欄位。
*/
function action_add_referer_field() { ?>
<div class="referer-field-wrap">
<label for="referer-field">轉介 ID</label>
<input type="text" name='referer-field' id='referer-field' value='<?php echo $_GET['referer'] ?>'>
</div>
<?php }
add_action( 'woocommerce_before_add_to_cart_button', 'action_add_referer_field' );
/**
* Add custom meta to order
*/
function action_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
// 如果購物車裡面有指定 'referer_id' 項目的值,就把該項目加入 order item meta data(保存於資料庫中)。
// 你將能夠在 wp_woocommerce_order_itemmeta 資料表中找到 'referer_id' 項目的名稱與值。
if ( isset( $values['referer_id'] ) ) {
$item->add_meta_data('referer_id', $values['referer_id'], true);
}
else {
$item->add_meta_data('referer_id', '(無)', true);
}
}
add_action( 'woocommerce_checkout_create_order_line_item', 'action_checkout_create_order_line_item', 10, 4 );
/**
* Add custom cart item data
*/
function filter_add_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
if( isset( $_POST['referer-field'] ) ) {
$cart_item_data['referer_id'] = sanitize_text_field( $_POST['referer-field'] );
}
else {
$cart_item_data['referer_id'] = '(無)';
}
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'filter_add_cart_item_data', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment