將自定義產品計算價格添加到 Woocommerce 購物車
php問題
html5模板網
Add a custom product calculated price to Woocommerce cart(將自定義產品計算價格添加到 Woocommerce 購物車)
本文介紹了將自定義產品計算價格添加到 Woocommerce 購物車的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
在 woocommerce 中,我在添加到購物車按鈕之前添加了一個額外的文本字段,以在產品購買時添加自定義費用.
此插件會為單個產品頁面添加額外的文本字段并計算總計加上額外費用.
我的問題是我無法添加自定義購物車總數,并且在總數之前添加額外費用
我嘗試了 woocommerce_cart_calculate_fees
但不幸的是它只顯示 $0
的總數
PHP 代碼:
/*** 檢查 woocommerce 是否處于活動狀態和/或已安裝.*/if ( class_exists( 'WooCommerce' ) || in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) || function_exists( 'WC' ) && is_object( WC() ) && is_a( WC(), 'WooCommerce' ) ){/*** 樣式和 Ajax 腳本.*/add_action('woocommerce_single_product_summary','extra_enqueue_scripts');函數 extra_enqueue_scripts(){wp_enqueue_style('custom_style', plugins_url('/assets/css/custom_style.css', __FILE__));wp_register_script('item_add', plugins_url('/assets/js/item_add.js', __FILE__), array('jquery'), false, true );wp_enqueue_script('item_add');$array_to_be_sent = array('ajax_file_path' => admin_url('admin-ajax.php'));wp_localize_script('item_add', 'wdm_object', $array_to_be_sent);}/*** 在添加到購物車按鈕之前添加文本字段.*/add_action( 'woocommerce_before_add_to_cart_button', 'extra_add_custom_field', 0 );函數 extra_add_custom_field(){$currency = get_woocommerce_currency_symbol();echo "<div class='custom-text text'><p>額外費用($currency):</p><input type='text' name='custom_price' value='' placeholder='e.g.10' title='自定義文本' class='custom_price text_custom text'></div>";}/*** 添加ajax回調函數獲取數據* 并將該數據添加到會話中.*/add_action('wp_ajax_extra_add_user_custom_data_options_callback', 'extra_add_user_custom_data_options_callback');add_action('wp_ajax_nopriv_extra_add_user_custom_data_options_callback', 'extra_add_user_custom_data_options_callback');函數 extra_add_user_custom_data_options_callback(){$user_custom_data_values = (float)sanitize_text_field($_POST['custom_price']);session_start();$_SESSION['user_custom_data'] = $user_custom_data_values;死();}/*** 將數據從會話添加到購物車,然后銷毀會話.*/add_filter('woocommerce_add_cart_item_data','extra_add_custom_field_data',1,2);功能 extra_add_custom_field_data($cart_item_data,$product_id){全球 $woocommerce;session_start();如果 (isset($_SESSION['user_custom_data'])){$option = $_SESSION['user_custom_data'];$new_value = array('user_custom_data_value' => $option);}如果(空($選項)){返回 $cart_item_data;}別的{如果(空($cart_item_data)){返回 $new_value;}別的{返回 array_merge($cart_item_data,$new_value);}}未設置($_SESSION['user_custom_data']);}/*** 從會話派生購物車項目.*/add_filter('woocommerce_get_cart_item_from_session', 'extra_get_cart_items_from_session', 1, 3);函數 extra_get_cart_items_from_session($item,$values,$key){如果(array_key_exists('user_custom_data_value',$values)){$item['user_custom_data_value'] = $values['user_custom_data_value'];}返回 $item;}/*** 在產品正常價格中添加額外價格.* 結帳前計算額外價格.*/add_action('woocommerce_before_calculate_totals', 'extra_price_add_custom_price');函數 extra_price_add_custom_price( $cart_object ){foreach ( $cart_object->get_cart() as $hash => $value ){if(!empty($value['user_custom_data_value']) && $value['data']->is_on_sale()){$newprice = $value['data']->get_sale_price() + $value['user_custom_data_value'];$value['data']->set_price((float)($newprice));}elseif(!empty($value['user_custom_data_value'])){$newprice = $value['data']->get_regular_price() + $value['user_custom_data_value'];$value['data']->set_price((float)($newprice));}}}/*** 在購物車表中顯示額外費用.*/add_filter('woocommerce_checkout_cart_item_quantity','extra_add_user_custom_option_from_session_into_cart',1,3);add_filter('woocommerce_cart_item_price','extra_add_user_custom_option_from_session_into_cart',1,3);功能 extra_add_user_custom_option_from_session_into_cart($product_name, $values, $cart_item_key ){if(count($values['user_custom_data_value']) > 0){$currency = get_woocommerce_currency_symbol();$product_price = wc_get_product( $values['product_id'] );if($product_price->is_on_sale()){$price = $product_price->get_sale_price().' (特價!)';}別的{$price = $product_price->get_regular_price();}$custom_items = $currency.$price."<br>";$custom_items .= $currency.$values['user_custom_data_value'].' ';$custom_items .= __("額外收費", "woocommerce");返回 $custom_items;}別的{返回 $product_name;}}/*** 如果數量為零,則刪除自定義數據.*/add_action('woocommerce_before_cart_item_quantity_zero','extra_remove_user_custom_data_options_from_cart',1,1);功能 extra_remove_user_custom_data_options_from_cart($cart_item_key){全球 $woocommerce;$cart = $woocommerce->cart->get_cart();foreach( $cart as $key => $values){if ( $values['user_custom_data_value'] == $cart_item_key ){取消設置($woocommerce->cart->cart_contents[$key]);}}}/*** 結帳后添加自定義數據以訂購元數據.*/add_action('woocommerce_add_order_item_meta','extra_add_values_to_order_item_meta',1,2);函數 extra_add_values_to_order_item_meta($item_id, $values){全球 $woocommerce,$wpdb;$user_custom_values = $values['user_custom_data_value'];if(!empty($user_custom_values)){$currency = get_woocommerce_currency_symbol();wc_add_order_item_meta($item_id,'額外費用',$currency.$user_custom_values);}}}別的{/*** 如果未檢測到 woocommerce,則生成錯誤通知.*/add_action('admin_notices', 'extra_no_woocommerce');函數 extra_no_woocommerce(){$err_text = site_url()."/wp-admin/plugin-install.php?tab=plugin-information&plugin=woocommerce&TB_iframe=true";?><div class="錯誤提示"><p><?php echo sprintf("請激活或 <a href='%s' style='color:green;'>安裝 Woocommerce</a> 以使用額外的字段進行產品收費插件",$err_text);?></p>
<?php}}
JS 代碼
jQuery(document).ready(function(){jQuery('.single_add_to_cart_button').click(function(){jQuery.ajax({網址:wdm_object.ajax_file_path,類型:POST",數據: {動作:'add_user_custom_data_options_callback',custom_price : jQuery('.custom_price').val()},異步:假,成功:功能(數據){jQuery('.single_add_to_cart_button').text('加入購物車');}});})});
解決方案
您不需要任何 javascript 或會話來實現這一點.請嘗試使用以下重新訪問的代碼:
//單次加入購物車前添加自定義字段add_action('woocommerce_before_add_to_cart_button', 'custom_product_price_field', 5);函數 custom_product_price_field(){echo '<p>額外費用('.get_woocommerce_currency_symbol().'):</p><input type="text" name="custom_price" value="" placeholder="e.g. 10" title="Custom Text" class="custom_price text_custom text">
';}//獲取自定義字段值,計算新商品價格,保存為自定義購物車商品數據add_filter('woocommerce_add_cart_item_data', 'add_custom_field_data', 20, 2 );函數 add_custom_field_data( $cart_item_data, $product_id ){if (!isset($_POST['custom_price']))返回 $cart_item_data;$custom_price = (float) sanitize_text_field( $_POST['custom_price'] );如果(空($custom_price))返回 $cart_item_data;$product = wc_get_product($product_id);//WC_Product 對象$base_price = (float) $product->get_regular_price();//產品注冊價格//新的價格計算$new_price = $base_price + $custom_price;//在購物車對象中設置自定義數量$cart_item_data['custom_data']['extra_charge'] = (float) $custom_price;$cart_item_data['custom_data']['new_price'] = (float) $new_price;$cart_item_data['custom_data']['unique_key'] = md5( microtime() . rand() );//使每個項目都是唯一的返回 $cart_item_data;}//設置新計算的購物車商品價格add_action('woocommerce_before_calculate_totals', 'extra_price_add_custom_price', 20, 1 );功能 extra_price_add_custom_price( $cart ) {if ( is_admin() && !defined( 'DOING_AJAX' ) )返回;if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )返回;foreach ( $cart->get_cart() as $cart_item ) {if( isset($cart_item['custom_data']['new_price']) )$cart_item['data']->set_price( (float) $cart_item['custom_data']['new_price'] );}}//顯示購物車項目自定義價格詳細信息add_filter('woocommerce_cart_item_price', 'display_cart_items_custom_price_details', 20, 3);功能 display_cart_items_custom_price_details( $product_price, $cart_item, $cart_item_key ){if( isset($cart_item['custom_data']['extra_charge']) ) {$product = $cart_item['data'];$product_price = wc_price( wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) );$product_price .= '
'.wc_price( $cart_item['custom_data']['extra_charge'] ).' ';$product_price .= __("額外收費", "woocommerce");}返回 $product_price;}
代碼位于活動子主題(或活動主題)的 function.php 文件中.經測試有效.
In woocommerce I have added an extra text field before add to cart button to add custom charge on product purchase.
This plugin will add extra text field to single product page and calculates total plus the extra charge.
My problem is that I cant add custom cart totals and the extra charge add before totals
I tried woocommerce_cart_calculate_fees
but no luck it only show $0
in totals
PHP code:
/**
* Check if woocommerce is active and or installed.
*/
if ( class_exists( 'WooCommerce' ) || in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) || function_exists( 'WC' ) && is_object( WC() ) && is_a( WC(), 'WooCommerce' ) )
{
/**
* Style and Ajax script.
*/
add_action('woocommerce_single_product_summary','extra_enqueue_scripts');
function extra_enqueue_scripts()
{
wp_enqueue_style('custom_style', plugins_url('/assets/css/custom_style.css', __FILE__));
wp_register_script( 'item_add', plugins_url('/assets/js/item_add.js', __FILE__), array('jquery'), false, true );
wp_enqueue_script('item_add');
$array_to_be_sent = array( 'ajax_file_path' => admin_url('admin-ajax.php'));
wp_localize_script( 'item_add', 'wdm_object', $array_to_be_sent);
}
/**
* Add Text field Before add to cart button.
*/
add_action( 'woocommerce_before_add_to_cart_button', 'extra_add_custom_field', 0 );
function extra_add_custom_field()
{
$currency = get_woocommerce_currency_symbol();
echo "<div class='custom-text text'><p>Extra Charge ($currency):</p>
<input type='text' name='custom_price' value='' placeholder='e.g. 10' title='Custom Text' class='custom_price text_custom text'></div>";
}
/**
* Add ajax callback function to get data
* and add that data to session.
*/
add_action('wp_ajax_extra_add_user_custom_data_options_callback', 'extra_add_user_custom_data_options_callback');
add_action('wp_ajax_nopriv_extra_add_user_custom_data_options_callback', 'extra_add_user_custom_data_options_callback');
function extra_add_user_custom_data_options_callback()
{
$user_custom_data_values = (float)sanitize_text_field($_POST['custom_price']);
session_start();
$_SESSION['user_custom_data'] = $user_custom_data_values;
die();
}
/**
* Add data to cart from session and then destroy session.
*/
add_filter('woocommerce_add_cart_item_data','extra_add_custom_field_data',1,2);
function extra_add_custom_field_data($cart_item_data,$product_id)
{
global $woocommerce;
session_start();
if (isset($_SESSION['user_custom_data']))
{
$option = $_SESSION['user_custom_data'];
$new_value = array('user_custom_data_value' => $option);
}
if(empty($option))
{
return $cart_item_data;
}
else
{
if(empty($cart_item_data))
{
return $new_value;
}
else
{
return array_merge($cart_item_data,$new_value);
}
}
unset($_SESSION['user_custom_data']);
}
/**
* Derive cart Item from session.
*/
add_filter('woocommerce_get_cart_item_from_session', 'extra_get_cart_items_from_session', 1, 3 );
function extra_get_cart_items_from_session($item,$values,$key)
{
if (array_key_exists( 'user_custom_data_value', $values ) )
{
$item['user_custom_data_value'] = $values['user_custom_data_value'];
}
return $item;
}
/**
* Add extra price into product regular price.
* Calculate extra price before checkout.
*/
add_action( 'woocommerce_before_calculate_totals', 'extra_price_add_custom_price' );
function extra_price_add_custom_price( $cart_object )
{
foreach ( $cart_object->get_cart() as $hash => $value )
{
if(!empty($value['user_custom_data_value']) && $value['data']->is_on_sale())
{
$newprice = $value['data']->get_sale_price() + $value['user_custom_data_value'];
$value['data']->set_price((float)( $newprice ));
}
elseif(!empty($value['user_custom_data_value']))
{
$newprice = $value['data']->get_regular_price() + $value['user_custom_data_value'];
$value['data']->set_price((float)( $newprice ));
}
}
}
/**
* Render extra charge in cart table.
*/
add_filter('woocommerce_checkout_cart_item_quantity','extra_add_user_custom_option_from_session_into_cart',1,3);
add_filter('woocommerce_cart_item_price','extra_add_user_custom_option_from_session_into_cart',1,3);
function extra_add_user_custom_option_from_session_into_cart($product_name, $values, $cart_item_key )
{
if(count($values['user_custom_data_value']) > 0)
{
$currency = get_woocommerce_currency_symbol();
$product_price = wc_get_product( $values['product_id'] );
if($product_price->is_on_sale())
{
$price = $product_price->get_sale_price().' (On Sale!)';
}
else
{
$price = $product_price->get_regular_price();
}
$custom_items = $currency.$price."<br>";
$custom_items .= $currency.$values['user_custom_data_value'].' ';
$custom_items .= __("Extra Charge", "woocommerce" );
return $custom_items;
}
else
{
return $product_name;
}
}
/**
* Remove custom data if quantity is zero.
*/
add_action('woocommerce_before_cart_item_quantity_zero','extra_remove_user_custom_data_options_from_cart',1,1);
function extra_remove_user_custom_data_options_from_cart($cart_item_key)
{
global $woocommerce;
$cart = $woocommerce->cart->get_cart();
foreach( $cart as $key => $values)
{
if ( $values['user_custom_data_value'] == $cart_item_key )
{
unset( $woocommerce->cart->cart_contents[ $key ] );
}
}
}
/**
* Add custom data to order meta after checkout.
*/
add_action('woocommerce_add_order_item_meta','extra_add_values_to_order_item_meta',1,2);
function extra_add_values_to_order_item_meta($item_id, $values)
{
global $woocommerce,$wpdb;
$user_custom_values = $values['user_custom_data_value'];
if(!empty($user_custom_values))
{
$currency = get_woocommerce_currency_symbol();
wc_add_order_item_meta($item_id,'Extra Charge',$currency.$user_custom_values);
}
}
}
else
{
/**
* Generate error notice if woocommerce is not detected.
*/
add_action( 'admin_notices', 'extra_no_woocommerce' );
function extra_no_woocommerce()
{
$err_text = site_url()."/wp-admin/plugin-install.php?tab=plugin-information&plugin=woocommerce&TB_iframe=true";
?>
<div class="error notice">
<p><?php echo sprintf("Please Activate or <a href='%s' style='color:green;'>Install Woocommerce</a> to use extra field for product charge plugin",$err_text); ?></p>
</div>
<?php
}
}
JS Code
jQuery(document).ready(function(){
jQuery('.single_add_to_cart_button').click(function(){
jQuery.ajax({
url: wdm_object.ajax_file_path,
type: "POST",
data: {
action:'add_user_custom_data_options_callback',
custom_price : jQuery('.custom_price').val()
},
async : false,
success: function(data){
jQuery('.single_add_to_cart_button').text('Added to cart');
}
});
})
});
解決方案
You don't need any javascript or sessions to achieve that. Try the following revisited code instead:
// Add a custom field before single add to cart
add_action( 'woocommerce_before_add_to_cart_button', 'custom_product_price_field', 5 );
function custom_product_price_field(){
echo '<div class="custom-text text">
<p>Extra Charge ('.get_woocommerce_currency_symbol().'):</p>
<input type="text" name="custom_price" value="" placeholder="e.g. 10" title="Custom Text" class="custom_price text_custom text">
</div>';
}
// Get custom field value, calculate new item price, save it as custom cart item data
add_filter('woocommerce_add_cart_item_data', 'add_custom_field_data', 20, 2 );
function add_custom_field_data( $cart_item_data, $product_id ){
if (! isset($_POST['custom_price']))
return $cart_item_data;
$custom_price = (float) sanitize_text_field( $_POST['custom_price'] );
if( empty($custom_price) )
return $cart_item_data;
$product = wc_get_product($product_id); // The WC_Product Object
$base_price = (float) $product->get_regular_price(); // Product reg price
// New price calculation
$new_price = $base_price + $custom_price;
// Set the custom amount in cart object
$cart_item_data['custom_data']['extra_charge'] = (float) $custom_price;
$cart_item_data['custom_data']['new_price'] = (float) $new_price;
$cart_item_data['custom_data']['unique_key'] = md5( microtime() . rand() ); // Make each item unique
return $cart_item_data;
}
// Set the new calculated cart item price
add_action( 'woocommerce_before_calculate_totals', 'extra_price_add_custom_price', 20, 1 );
function extra_price_add_custom_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
foreach ( $cart->get_cart() as $cart_item ) {
if( isset($cart_item['custom_data']['new_price']) )
$cart_item['data']->set_price( (float) $cart_item['custom_data']['new_price'] );
}
}
// Display cart item custom price details
add_filter('woocommerce_cart_item_price', 'display_cart_items_custom_price_details', 20, 3 );
function display_cart_items_custom_price_details( $product_price, $cart_item, $cart_item_key ){
if( isset($cart_item['custom_data']['extra_charge']) ) {
$product = $cart_item['data'];
$product_price = wc_price( wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ) );
$product_price .= '<br>' . wc_price( $cart_item['custom_data']['extra_charge'] ).' ';
$product_price .= __("Extra Charge", "woocommerce" );
}
return $product_price;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
這篇關于將自定義產品計算價格添加到 Woocommerce 購物車的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!