产品页面自定义复选框可在WooCommerce购物车小计上启用百分比折扣。

huangapple go评论117阅读模式
英文:

Product page custom checkbox enable a percentage discount on WooCommerce cart subtotal

问题

以下是代码部分的翻译:

目标很简单,在 **WooCommerce 产品页面** 上添加一个复选框。如果用户选中复选框,则将在购物车小计上应用 5% 的折扣。

我已经检查了代码,多次确认,但我就是无法弄清楚为什么会出现“致命错误”。

**这是代码:**

add_action( 'woocommerce_after_add_to_cart_button', 'ls_automatic_discount_checbox', 10 );
function ls_automatic_discount_checbox() {
    echo '<p><label><input type="checkbox" name="apply_automatic_discount" value="1"/> 应用 5% 的折扣到您的小计</label></p>';
}

add_action( 'woocommerce_cart_calculate_fees', 'ls_apply_discount_on_checkbox_check', 10, 7 );
function ls_apply_discount_on_checkbox_check( $cart, $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {

        // 确保复选框被选中
        if ( isset( $_POST['apply_automatic_discount'] ) && $_POST['apply_automatic_discount'] == 1 ) {        

        // 如果是这样,检查小计的折扣百分比
        $percent = 5;

        // 如果一切正常 - 给予折扣
        if ( isset ( $percent ) && $percent > 0 ) {

        // 客户将获得小计的 5% 折扣
        $discount = $cart->cart_contents_total * $percent / 100;
        $cart->add_fee( __('5% OFF', 'woocommerce' ) . " (" . $percent . "%)", -$discount);
    
        }
    }
}
英文:

The goal is simple, add a checkbox to the WooCommerce Product Page. If the user checks the checkbox, a 5% discount is applied on cart subtotal.

I have checked and doubled checked the code like ten times, I just cannot figure out why it gives me the "Fatal Error".

This is the code:

add_action( &#39;woocommerce_after_add_to_cart_button&#39;, &#39;ls_automatic_discount_checbox&#39;, 10 );
function ls_automatic_discount_checbox() {
    echo &#39;&lt;p&gt;&lt;label&gt;&lt;input type=&quot;checkbox&quot; name=&quot;apply_automatic_discount&quot; value=&quot;1&quot;/&gt; Apply 5% discount to your subtotal&lt;/label&gt;&lt;/p&gt;&#39;;
}

add_action( &#39;woocommerce_cart_calculate_fees&#39;, &#39;ls_apply_discount_on_checkbox_check&#39;, 10, 7 );
function ls_apply_discount_on_checkbox_check( $cart, $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {

        // makes sure that the checkbox is ticked
        if ( isset( $_POST[ &#39;apply_automatic_discount&#39; ] ) &amp;&amp; $_POST[ &#39;apply_automatic_discount&#39; ] == 1 ) {        

        // if it is, check what the percentaged discount on the subtotal is
        $percent = 5;

        // if all checks out - give the discount
        if ( isset ( $percent ) &amp;&amp; $percent &gt; 0 ) {

        // customer gets a discount of 5% of the SUBTOTAL
        $discount = $cart-&gt;cart_contents_total * $percent / 100;
        $cart-&gt;add_fee( __(&#39;5% OFF&#39;, &#39;woocommerce&#39; ) . &quot; (&quot; . $percent . &quot;%)&quot;, -$discount);
    
        }
    }
}

答案1

得分: 2

以下是您的代码中需要修复的问题和错误:

  • 首先,您需要将复选框的值保存为自定义购物车项目数据。
  • woocommerce_cart_calculate_fees 钩子只有一个参数:$cartWC_Cart 对象)。这是主要的错误问题。
  • 您可以将 woocommerce_after_add_to_cart_button 钩子(在添加到购物车按钮后显示复选框)替换为 woocommerce_before_add_to_cart_button,以在之前显示复选框,这更符合逻辑。

代码如下:

add_action('woocommerce_after_add_to_cart_button', 'ls_automatic_discount_checbox', 10);
function ls_automatic_discount_checbox() {
    printf('<p class="auto-discount"><label><input type="checkbox" name="auto_discount" value="1"/> %s</label></p>',
        __('Apply 5% discount to your subtotal', 'woocommerce'));
}

// 添加自定义购物车项目数据
add_filter('woocommerce_add_cart_item_data', 'add_custom_field_value_to_cart_item_data', 10, 2);
function add_custom_field_value_to_cart_item_data($cart_item_data, $product_id) {
    $cart_item_data['auto_discount'] = isset($_POST['auto_discount']) ? '1' : '0';
    return $cart_item_data;
}

现在,您可以全局或按产品添加折扣(已选中复选框的产品):

A/. 全局(对购物车小计):

add_action('woocommerce_cart_calculate_fees', 'auto_applied_product_discount', 10);
function auto_applied_product_discount($cart) {
    if (is_admin() && !defined('DOING_AJAX'))
        return;

    $auto_discount = false; // 初始化

    // 遍历购物车项目
    foreach ($cart->get_cart() as $cart_item) {
        if (isset($cart_item['auto_discount']) && $cart_item['auto_discount']) {
            $auto_discount = true;
            break; // 停止循环
        }
    }
    
    if ($auto_discount) {
        $percent = 5;
        $total = $cart->cart_contents_total;
        $cart->add_fee(__('5% OFF', 'woocommerce') . " (" . $percent . "%)", -($total * $percent / 100));
    }
}

B/. 按产品小计(已选中复选框的产品):

add_action('woocommerce_cart_calculate_fees', 'auto_applied_product_discount', 10);
function auto_applied_product_discount($cart) {
    if (is_admin() && !defined('DOING_AJAX'))
        return;

    $total = 0; // 初始化

    // 遍历购物车项目
    foreach ($cart->get_cart() as $cart_item) {
        if (isset($cart_item['auto_discount']) && $cart_item['auto_discount']) {
            $total += $cart_item['line_total'];
        }
    }
    
    if ($total > 0) {
        $percent = 5;
        $cart->add_fee(__('5% OFF', 'woocommerce') . " (" . $percent . "%)", -($total * $percent / 100));
    }
}

将此代码放在您子主题的 functions.php 文件中(或插件中)。已测试并正常工作。

英文:

There are some missing things and mistakes in your code:

  • 1st, you need to save the checkbox value as custom cart item data.
  • the hook woocommerce_cart_calculate_feeshas only one argument: $cart (the WC_Cart object). That was the main error issue.
  • You could replace woocommerce_after_add_to_cart_button hook (that displays the checkbox after add to cart button) with woocommerce_before_add_to_cart_button, to display the checkbox before, which is more logical.

The code:

add_action( &#39;woocommerce_after_add_to_cart_button&#39;, &#39;ls_automatic_discount_checbox&#39;, 10 );
function ls_automatic_discount_checbox() {
    printf( &#39;&lt;p class=&quot;auto-discount&quot;&gt;&lt;label&gt;&lt;input type=&quot;checkbox&quot; name=&quot;auto_discount&quot; value=&quot;1&quot;/&gt; %s&lt;/label&gt;&lt;/p&gt;&#39;, 
        __(&#39;Apply 5% discount to your subtotal&#39;, &#39;woocommerce&#39;) );
}

// Add custom cart item data
add_filter(&#39;woocommerce_add_cart_item_data&#39;, &#39;add_custom_field_value_to_cart_item_data&#39;, 10, 2);
function add_custom_field_value_to_cart_item_data($cart_item_data, $product_id) {
    $cart_item_data[&#39;auto_discount&#39;] = isset($_POST[&#39;auto_discount&#39;]) ? &#39;1&#39; : &#39;0&#39;;
    return $cart_item_data;
}

Now you can add a discount globally or by product (where the checkbox has been checked):

A/. Globally (on the cart subtotal):

add_action( &#39;woocommerce_cart_calculate_fees&#39;, &#39;auto_applied_product_discount&#39;, 10 );
function auto_applied_product_discount( $cart ) {
    if ( is_admin() &amp;&amp; ! defined( &#39;DOING_AJAX&#39; ) )
        return;

    $auto_discount = false; // Initializing

    // Loop through cart items
    foreach ( $cart-&gt;get_cart() as $cart_item ) {
        if ( isset($cart_item[&#39;auto_discount&#39;]) &amp;&amp; $cart_item[&#39;auto_discount&#39;] ) {
            $auto_discount = true;
            break; // Stop the loop
        }
    }
    
    if ( $auto_discount ) {
        $percent  = 5;
        $total    = $cart-&gt;cart_contents_total;
        $cart-&gt;add_fee( __(&#39;5% OFF&#39;, &#39;woocommerce&#39; ) . &quot; (&quot; . $percent . &quot;%)&quot;, -($total * $percent / 100));
    }
}

B/. By product subtotal (where the checkbox has been checked):

add_action( &#39;woocommerce_cart_calculate_fees&#39;, &#39;auto_applied_product_discount&#39;, 10 );
function auto_applied_product_discount( $cart ) {
    if ( is_admin() &amp;&amp; ! defined( &#39;DOING_AJAX&#39; ) )
        return;

    $total = 0; // Initializing

    // Loop through cart items
    foreach ( $cart-&gt;get_cart() as $cart_item ) {
        if ( isset($cart_item[&#39;auto_discount&#39;]) &amp;&amp; $cart_item[&#39;auto_discount&#39;] ) {
            $total += $cart_item[&#39;line_total&#39;];
        }
    }
    
    if ( $total &gt; 0 ) {
        $percent  = 5;
        $cart-&gt;add_fee( __(&#39;5% OFF&#39;, &#39;woocommerce&#39; ) . &quot; (&quot; . $percent . &quot;%)&quot;, -($total * $percent / 100));
    }
}

Code goes in functions.php file of your child theme (or in a plugin). Tested and works.

huangapple
  • 本文由 发表于 2023年8月10日 21:53:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76876404.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定