php 将自定义字段添加到购物车/结帐
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 将自定义字段添加到购物车/结帐相关的知识,希望对你有一定的参考价值。
// 1. CREATE CUSTOM SHIPPING PRICE FIELD
function custom_field_shipping() {
$args = array(
'id' => 'custom-shipping-field',
'label' => __( 'Additional Shipping Charges', 'pmctool' ),
'class' => 'custom-field',
'desc_tip' => true,
'description' => __( 'If this product has additional shipping charges that will be added at checkout, enter them here including the $ sign.', 'pmctool' ),
);
woocommerce_wp_text_input( $args ); }
add_action( 'woocommerce_product_options_shipping', 'custom_field_shipping' );
// 2. SAVE CUSTOM SHIPPING PRICE FIELD
function save_custom_field_shipping( $post_id ) {
$product = wc_get_product( $post_id );
$title = isset( $_POST['custom-shipping-field'] ) ? $_POST['custom-shipping-field'] : '';
$product->update_meta_data( 'custom-shipping-field', sanitize_text_field( $title ) );
$product->save(); }
add_action( 'woocommerce_process_product_meta', 'save_custom_field_shipping' );
// 3. DISPLAY CUSTOM SHIPPING PRICE FIELD
function add_shipping_cost_to_cart( $cart_data, $cart_item ) {
$custom_items = array();
if( !empty( $cart_data ) )
$custom_items = $cart_data;
// Get the product ID
$product_id = $cart_item['product_id'];
if( $custom_field_value = get_post_meta( $product_id, 'custom-shipping-field', true ) )
$custom_items[] = array(
'name' => __( 'Freight', 'woocommerce' ),
'value' => $custom_field_value,
'display' => '<span class="custom-shipping-costs">+ $' . $custom_field_value . ' Shipping</span>',
);
return $custom_items; }
add_filter( 'woocommerce_get_item_data', 'add_shipping_cost_to_cart', 10, 2 );
// 4. MULTIPLY BY QUANTITY IN CART
function add_shipping_cost_to_cart( $cart_data, $cart_item ) {
$custom_items = array();
if( !empty( $cart_data ) )
$custom_items = $cart_data;
// Get the product ID
$product_id = $cart_item['product_id'];
$qty = $cart_item['quantity'];
if( $custom_field_value = get_post_meta( $product_id, 'custom-shipping-field', true ) )
$custom_items[] = array(
'name' => __( 'Freight', 'woocommerce' ),
'value' => $custom_field_value,
'display' => '<span class="custom-shipping-costs"> $' . $custom_field_value . ' x ' . $qty . ' = $' . $custom_field_value * $qty . ' Shipping</span>',
);
return $custom_items; }
add_filter( 'woocommerce_get_item_data', 'add_shipping_cost_to_cart', 10, 2 );
// Reference: https://stackoverflow.com/questions/43893196/display-custom-fields-value-in-woocommerce-cart-checkout-items
以上是关于php 将自定义字段添加到购物车/结帐的主要内容,如果未能解决你的问题,请参考以下文章
WooCommerce:将自定义 Metabox 添加到管理订单页面
Drupal,Ubercart - 将自定义字段添加到结帐表单
在产品中添加自定义字段以显示在购物车、结帐和订单中
在 Woocommerce 购物车、结帐页面、订单和电子邮件通知中的产品标题上方显示品牌名称
有没有办法将自定义代码添加到公共静态函数中? (woocommerce update_order_review)
php [使用操作和过滤器自定义结帐字段]清空购物车重定向网址