在 Woocommerce 中,我想根据客户总购买金额设置百分比折扣。例如,如果总购买金额大于或等于200$,客户将获得5%折扣。。 p>
所以,我有第一部分代码来显示总和:
function get_customer_total_order() {
$customer_orders = get_posts( array(
'numberposts' => - 1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => array( 'shop_order' ),
'post_status' => array( 'wc-completed' )
) );
$total = 0;
foreach ( $customer_orders as $customer_order ) {
$order = wc_get_order( $customer_order );
$total += $order->get_total();
}
return $total;
}
我想将我的代码与这个答案的代码一起使用:
Progressive discount based on cart total in WooCommerce
有没有办法同时使用它们来根据所有订单的总和设置折扣?
最佳答案
有多种方法可以获取客户的总购买金额:
1) 您可以使用 wc_get_customer_total_spent() 替换您的第一个函数专用的 Woocommerce 功能,但此功能获取所有订单的已付款状态(“正在处理”和“已完成”)。
2) 你也可以使用这个基于 similar source code 的更简单的 SQL 查询仅针对“已完成”订单状态:
// Utililty function to get customer's total purchases sum
function get_customer_total_purchases_sum() {
$current_user_id = get_current_user_id(); // Current user ID
if( $current_user_id == 0 ) return 0; // we return zero if customer is not logged in
global $wpdb;
// return the SQL query (paid orders sum)
return $wpdb->get_var("SELECT SUM(pm.meta_value) FROM {$wpdb->prefix}postmeta as pm
INNER JOIN {$wpdb->prefix}postmeta as pm2 ON pm.post_id = pm2.post_id
INNER JOIN {$wpdb->prefix}posts as p ON pm.post_id = p.ID
WHERE p.post_status LIKE 'wc-completed' AND p.post_type LIKE 'shop_order'
AND pm.meta_key LIKE '_order_total' AND pm2.meta_key LIKE '_customer_user'
AND pm2.meta_value LIKE '$current_user_id'");
}
此代码位于您的事件子主题(或主题)的 function.php 文件中。经过测试并有效。
3) 或者你可以使用你自己的问题功能代码(但它更重)。这取决于你。
1) 负费用:
以下代码将根据客户的总购买金额设置百分比折扣(使用我上面的函数):
// Percentage discount based on customer's total purchases sum
add_action('woocommerce_cart_calculate_fees', 'customer_purchases_total_sum_percentage_discount', 20, 1 );
function customer_purchases_total_sum_percentage_discount( $cart ){
// Only for logged in user
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_user_logged_in() )
return;
## 1. Get the customer's purchases total sum (and save it in WC sessions to avoid multiple queries
// Check if it's saved in WC_Session
$purchases_sum = WC()->session->get( 'purchases_sum' );
// If not get it and save it
if( empty($purchases_sum) ){
// ==> HERE goes the function to get customer's purchases total sum
$purchases_sum = get_customer_total_purchases_sum();
// Save it in WC_Session
WC()->session->set('purchases_sum', $purchases_sum);
}
## 2. Set the discount percentage based on customer's total purchases sum
if( $purchases_sum >= 200 ){
$percent = 5; // 5%
}
if( isset($percent) && $percent > 0){
$discount = $cart->cart_contents_total * $percent / 100; // discount calculation
// Set the discount (For discounts (negative fee) the taxes as always included)
$cart->add_fee( __('Discount', 'woocommerce' ) . " (" . $percent . "%)", -$discount);
}
}
此代码位于您的事件子主题(或主题)的 function.php 文件中。经过测试并有效。
2) 自动添加优惠券代码(百分比折扣):
首先您需要设置一个新的优惠券代码(百分比折扣类型为 5%):
然后您将使用以下代码代替,它会根据客户的总购买金额自动添加优惠券代码(使用我上面的函数):
add_action( 'woocommerce_before_calculate_totals', 'customer_total_purchases_coupon_discount', 30, 1 );
function customer_total_purchases_coupon_discount( $cart ) {
// Only for logged in user
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_user_logged_in() )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// HERE define your coupon code (in lowercase)
$coupon_code = 'customersilver';
## 1. Get the customer's purchases total sum (and save it in WC sessions to avoid multiple queries
// Check if it's saved in WC_Session
$purchases_sum = WC()->session->get( 'purchases_sum' );
// If not get it and save it
if( empty($purchases_sum) ){
// ==> HERE goes the function to get customer's purchases total sum
$purchases_sum = get_customer_total_purchases_sum();
// Save it in WC_Session
WC()->session->set('purchases_sum', $purchases_sum);
}
## 2. Auto applying or removing a coupon code (percentage discount coupon)
// Apply the coupon if there is at least 2 units of "5 Reusable wet"
if ( ! $cart->has_discount( $coupon_code ) && $purchases_sum >= 200 ) {
$cart->add_discount( $coupon_code );
} elseif( $cart->has_discount( $coupon_code ) && $purchases_sum < 200 ) {
$cart->remove_coupon( $coupon_code );
}
}
此代码位于您的事件子主题(或主题)的 function.php 文件中。经过测试并有效。
关于php - 在 Woocommerce 中根据客户总购买金额添加百分比折扣,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52141772/
当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/
我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它
我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以
我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden
当谈到运行时自省(introspection)和动态代码生成时,我认为ruby没有任何竞争对手,可能除了一些lisp方言。前几天,我正在做一些代码练习来探索ruby的动态功能,我开始想知道如何向现有对象添加方法。以下是我能想到的3种方法:obj=Object.new#addamethoddirectlydefobj.new_method...end#addamethodindirectlywiththesingletonclassclass这只是冰山一角,因为我还没有探索instance_eval、module_eval和define_method的各种组合。是否有在线/离线资
我注意到类定义,如果我打开classMyClass,并在不覆盖的情况下添加一些东西我仍然得到了之前定义的原始方法。添加的新语句扩充了现有语句。但是对于方法定义,我仍然想要与类定义相同的行为,但是当我打开defmy_method时似乎,def中的现有语句和end被覆盖了,我需要重写一遍。那么有什么方法可以使方法定义的行为与定义相同,类似于super,但不一定是子类? 最佳答案 我想您正在寻找alias_method:classAalias_method:old_func,:funcdeffuncold_func#similartoca
我有带有Logo图像的公司模型has_attached_file:logo我用他们的Logo创建了许多公司。现在,我需要添加新样式has_attached_file:logo,:styles=>{:small=>"30x15>",:medium=>"155x85>"}我是否应该重新上传所有旧数据以重新生成新样式?我不这么认为……或者有什么rake任务可以重新生成样式吗? 最佳答案 参见Thumbnail-Generation.如果rake任务不适合你,你应该能够在控制台中使用一个片段来调用重新处理!关于相关公司
我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_
我正在开发一个创建网络博客的RubyonRails项目。我希望将一个名为featured的boolean数据库字段添加到Post模型中。该字段应该可以通过我添加的事件管理界面进行编辑。我使用了以下代码,但我什至没有在网站上显示另一列。$railsgeneratemigrationaddFeaturedfeatured:boolean$rakedb:migrate我是RubyonRails的新手,非常感谢任何帮助。我的index.html.erb文件中的相关代码(views):FeaturedPost架构.rb:ActiveRecord::Schema.define(:version=>
我有一个使用SeleniumWebdriver和Nokogiri的Ruby应用程序。我想选择一个类,然后对于那个类对应的每个div,我想根据div的内容执行一个Action。例如,我正在解析以下页面:https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=puppies这是一个搜索结果页面,我正在寻找描述中包含“Adoption”一词的第一个结果。因此机器人应该寻找带有className:"result"的div,对于每个检查它的.descriptiondiv是否包含单词“adoption