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 display_custom_field_shipping() {
$title = get_post_meta( get_the_ID(), 'custom-shipping-field', true );
if( $title ) {
echo '<span class="custom-shipping-costs">+ $' . $title . ' Shipping or FREE In-Store Pickup</span>';
}
}
add_action( 'woocommerce_before_add_to_cart_form', 'display_custom_field_shipping' );
// 4. MULTIPLY BY QUANTITY IN CART AND ADD SHIPPING COST TO 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 or FREE In-Store Pickup</span>',
);
return $custom_items;
}
add_filter( 'woocommerce_get_item_data', 'add_shipping_cost_to_cart', 10, 2 );
// Reference: https://pluginrepublic.com/add-custom-fields-woocommerce-product/#saving-custom-field-value
// Reference: https://www.liquidweb.com/blog/custom-fields-woocommerce-products/
//
以上是关于php 创建自定义“+ $$$运输”字段的主要内容,如果未能解决你的问题,请参考以下文章
Woocommerce 3中的自定义结帐字段和运输方式ajax交互
Woocommerce 设置计费和运输信息
如何在 Woocommerce 中获取运输方式自定义附加数据?
PHP 自定义字段 - 创建帖子系列
在创建后设置自定义选择字段的默认值(wordpress PHP jquery)
将运输方式和时间段添加到 woocommerce 电子邮件 [重复]