wordpress 独立站设置动态阶梯价格教程 可以根据客户订购的数量设置不通的优惠金额

// 添加后台菜单
add_action('admin_menu', 'add_bulk_discount_menu');
function add_bulk_discount_menu() {
    add_menu_page(
        '批量折扣设置',
        '批量折扣',
        'manage_options',
        'bulk-discount-settings',
        'bulk_discount_settings_page',
        'dashicons-tag',
        56
    );
}

// 注册设置
add_action('admin_init', 'register_bulk_discount_settings');
function register_bulk_discount_settings() {
    register_setting('bulk_discount_options', 'bulk_discount_rules');
}

// 创建设置页面
function bulk_discount_settings_page() {
    $rules = get_option('bulk_discount_rules', array(
        array(
            'min' => 1,
            'max' => 100,
            'discount' => 99,
            'label' => '1-100件'
        )
    ));
    ?>
    <div class="wrap">
        <h1>批量折扣设置</h1>
        <form method="post" action="options.php" id="bulk-discount-form">
            <?php settings_fields('bulk_discount_options'); ?>
            
            <div class="discount-rules-container">
                <h2>折扣规则</h2>
                <p class="description">设置不同数量范围的折扣百分比,例如:数量1-100,折扣99%表示99折</p>
                <table class="wp-list-table widefat fixed striped" id="discount-rules-table">
                    <thead>
                        <tr>
                            <th>最小数量</th>
                            <th>最大数量</th>
                            <th>折扣(%)</th>
                            <th>描述</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="discount-rules-body">
                        <?php foreach ($rules as $index => $rule): ?>
                        <tr class="rule-row">
                            <td>
                                <input type="number" name="bulk_discount_rules[<?php echo $index; ?>][min]" 
                                       value="<?php echo esc_attr($rule['min']); ?>" required min="1">
                            </td>
                            <td>
                                <input type="number" name="bulk_discount_rules[<?php echo $index; ?>][max]" 
                                       value="<?php echo esc_attr($rule['max']); ?>" required min="1">
                            </td>
                            <td>
                                <input type="number" name="bulk_discount_rules[<?php echo $index; ?>][discount]" 
                                       value="<?php echo esc_attr($rule['discount']); ?>" required min="1" max="100" step="0.1">
                            </td>
                            <td>
                                <input type="text" name="bulk_discount_rules[<?php echo $index; ?>][label]" 
                                       value="<?php echo esc_attr($rule['label']); ?>" required>
                            </td>
                            <td>
                                <button type="button" class="button delete-rule">删除</button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                
                <div class="rule-actions">
                    <button type="button" class="button button-secondary" id="add-rule">添加规则</button>
                    <button type="submit" class="button button-primary">保存设置</button>
                </div>
            </div>
        </form>
    </div>

    <style>
        .discount-rules-container {
            margin-top: 20px;
            max-width: 1000px;
        }
        .rule-row input {
            width: 100%;
        }
        .rule-actions {
            margin-top: 20px;
        }
        .delete-rule {
            color: #dc3232;
        }
        #discount-rules-table {
            margin-top: 10px;
        }
        #discount-rules-table th,
        #discount-rules-table td {
            padding: 10px;
        }
        .description {
            color: #666;
            font-style: italic;
            margin-bottom: 15px;
        }
    </style>

    <script>
    jQuery(document).ready(function($) {
        // 添加新规则
        $('#add-rule').click(function() {
            var rowCount = $('.rule-row').length;
            var newRow = `
                <tr class="rule-row">
                    <td>
                        <input type="number" name="bulk_discount_rules[${rowCount}][min]" required min="1">
                    </td>
                    <td>
                        <input type="number" name="bulk_discount_rules[${rowCount}][max]" required min="1">
                    </td>
                    <td>
                        <input type="number" name="bulk_discount_rules[${rowCount}][discount]" required min="1" max="100" step="0.1">
                    </td>
                    <td>
                        <input type="text" name="bulk_discount_rules[${rowCount}][label]" required>
                    </td>
                    <td>
                        <button type="button" class="button delete-rule">删除</button>
                    </td>
                </tr>
            `;
            $('#discount-rules-body').append(newRow);
        });

        // 删除规则
        $(document).on('click', '.delete-rule', function() {
            $(this).closest('tr').remove();
            reindexRows();
        });

        // 重新索引行
        function reindexRows() {
            $('.rule-row').each(function(index) {
                $(this).find('input').each(function() {
                    var name = $(this).attr('name');
                    $(this).attr('name', name.replace(/\[\d+\]/, '[' + index + ']'));
                });
            });
        }
    });
    </script>
    <?php
}

// 获取折扣规则
function get_quantity_discount_rules() {
    $rules = get_option('bulk_discount_rules', array());
    $formatted_rules = array();
    
    foreach ($rules as $rule) {
        $formatted_rules[] = array(
            'min' => intval($rule['min']),
            'max' => intval($rule['max']),
            'discount' => floatval($rule['discount']) / 100,
            'label' => $rule['label']
        );
    }
    
    return $formatted_rules;
}

// 获取特定数量对应的折扣
function get_discount_for_quantity($quantity) {
    $rules = get_quantity_discount_rules();
    foreach ($rules as $rule) {
        if ($quantity >= $rule['min'] && $quantity <= $rule['max']) {
            return $rule['discount'];
        }
    }
    return 1; // 如果没有匹配的规则,返回原价
}

// 在产品详情页显示价格表
add_action('woocommerce_single_product_summary', 'display_quantity_discount_table', 11);
function display_quantity_discount_table() {
    global $product;
    
    $price = $product->get_price();
    $rules = get_quantity_discount_rules();
    
    if (empty($rules)) {
        return;
    }
    
    echo '<div class="quantity-discount-table">';
    echo '<div class="discount-table-header">';
    echo '<span class="discount-title">Bulk Pricing</span>';
    echo '<span class="discount-info">Buy more, save more!</span>';
    echo '</div>';
    echo '<table class="discount-table">';
    echo '<thead>';
    echo '<tr>';
    echo '<th>Quantity</th>';
    echo '<th>Discount</th>';
    echo '<th>Price</th>';
    echo '</tr>';
    echo '</thead>';
    echo '<tbody>';
    
    foreach ($rules as $rule) {
        $discounted_price = number_format($price * $rule['discount'], 2);
        $discount_percentage = 100 - ($rule['discount'] * 100);
        echo '<tr>';
        echo '<td>' . esc_html($rule['label']) . '</td>';
        echo '<td>' . number_format($discount_percentage, 1) . '% OFF</td>';
        echo '<td>$' . $discounted_price . '</td>';
        echo '</tr>';
    }
    
    echo '</tbody>';
    echo '</table>';
    echo '</div>';
}

// 修改产品列表页的价格显示
add_filter('woocommerce_get_price_html', 'modify_price_range_display', 100, 2);
function modify_price_range_display($price_html, $product) {
    if (is_product()) {
        return $price_html;
    }
    
    $rules = get_quantity_discount_rules();
    if (empty($rules)) {
        return $price_html;
    }
    
    $price = $product->get_price();
    $prices = array();
    
    foreach ($rules as $rule) {
        $prices[] = $price * $rule['discount'];
    }
    
    if (!empty($prices)) {
        $min_price = min($prices);
        $max_price = max($prices);
        
        return sprintf(
            '<span class="woocs_price_code" data-currency="">
                <span class="woocommerce-Price-amount amount">
                    <bdi>%s-%s<span class="woocommerce-Price-currencySymbol">$</span></bdi>
                </span>
            </span>',
            number_format($min_price, 2),
            number_format($max_price, 2)
        );
    }
    
    return $price_html;
}

// 添加样式
add_action('wp_head', 'add_discount_table_styles');
function add_discount_table_styles() {
    ?>
    <style>
        /* 价格表样式优化 */
        .quantity-discount-table {
            margin: 15px 0;
            background: #fff;
            border: 1px solid #e1e1e1;
            border-radius: 6px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
            font-size: 14px;
            max-width: 400px;
        }
        
        .discount-table-header {
            padding: 10px 15px;
            border-bottom: 1px solid #e1e1e1;
            background: #f8f9fa;
            border-radius: 6px 6px 0 0;
        }
        
        .discount-title {
            display: block;
            font-weight: 600;
            color: #2c3338;
            font-size: 15px;
            margin-bottom: 2px;
        }
        
        .discount-info {
            display: block;
            color: #666;
            font-size: 12px;
        }
        
        .discount-table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .discount-table th,
        .discount-table td {
            padding: 8px 12px;
            text-align: center;
            border: none;
            border-bottom: 1px solid #e1e1e1;
            font-size: 13px;
        }
        
        .discount-table th {
            background: #fff;
            color: #666;
            font-weight: 500;
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .discount-table tr:last-child td {
            border-bottom: none;
        }
        
        .discount-table td:first-child {
            color: #2c3338;
            font-weight: 500;
        }
        
        .discount-table td:nth-child(2) {
            color: #28a745;
            font-weight: 500;
        }
        
        .discount-table td:last-child {
            color: #2c3338;
            font-weight: 600;
        }
        
        .discount-table tr:hover {
            background: #f8f9fa;
        }
        
        /* 购物车折扣信息样式 */
        .cart-discount-info {
            font-size: 12px;
            color: #28a745;
            margin-top: 4px;
            padding: 2px 6px;
            background: #e8f5e9;
            border-radius: 3px;
            display: inline-block;
        }
        
        /* 购物车顶部折扣提示样式 */
        .cart-discount-notice {
            background: #f8f9fa;
            padding: 12px 15px;
            border-radius: 6px;
            margin-bottom: 20px;
            border: 1px solid #e1e1e1;
            font-size: 14px;
        }
        
        .cart-discount-notice h4 {
            margin: 0 0 8px 0;
            color: #2c3338;
            font-size: 16px;
        }
        
        .cart-discount-notice table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 8px;
            font-size: 13px;
        }
        
        .cart-discount-notice th,
        .cart-discount-notice td {
            padding: 6px 8px;
            border: 1px solid #e1e1e1;
            text-align: center;
        }
        
        .cart-discount-notice th {
            background: #f0f0f0;
            font-weight: 500;
        }
        
        /* 移动端适配 */
        @media (max-width: 768px) {
            .quantity-discount-table {
                font-size: 13px;
                margin: 10px 0;
            }
            
            .discount-table th,
            .discount-table td {
                padding: 6px 8px;
            }
            
            .cart-discount-notice {
                font-size: 13px;
                padding: 10px;
            }
        }
    </style>
    <?php
}

// 修改购物车中的商品价格
add_action('woocommerce_before_calculate_totals', 'apply_quantity_based_discount', 20, 1);
function apply_quantity_based_discount($cart) {
    if (is_admin() && !defined('DOING_AJAX')) {
        return;
    }

    // 防止多次执行
    if (did_action('woocommerce_before_calculate_totals') >= 2) {
        return;
    }

    // 遍历购物车中的每个商品
    foreach ($cart->get_cart() as $cart_item) {
        $quantity = $cart_item['quantity'];
        $product = $cart_item['data'];

        // 获取产品的促销价格(如果有)
        $sale_price = $product->get_sale_price();
        $regular_price = $product->get_regular_price();

        // 如果产品有促销价格,则使用促销价格,否则使用原价
        $price_to_apply = $sale_price ? $sale_price : $regular_price;

        // 获取适用的折扣
        $discount = get_discount_for_quantity($quantity);

        // 根据折扣计算新的价格
        $discounted_price = $price_to_apply * $discount;

        // 更新购物车商品价格
        $cart_item['data']->set_price($discounted_price);
    }
}

// 在购物车页面显示折扣信息
add_action('woocommerce_after_cart_item_name', 'display_cart_item_discount', 10, 2);
function display_cart_item_discount($cart_item, $cart_item_key) {
    $quantity = $cart_item['quantity'];
    $discount = get_discount_for_quantity($quantity);
    $discount_percentage = (1 - $discount) * 100;
    
    if ($discount < 1) {
        echo '<div class="cart-discount-info">';
        echo sprintf('%.1f%% OFF applied for quantity of %d', $discount_percentage, $quantity);
        echo '</div>';
    }
}

// 在购物车页面显示数量变化时的价格更新提示
add_action('wp_footer', 'add_quantity_change_script');
function add_quantity_change_script() {
    if (!is_cart()) return;
    ?>
    <script>
    jQuery(document).ready(function($) {
        var timeout;
        
        $('.quantity input.qty').on('change', function() {
            clearTimeout(timeout);
            timeout = setTimeout(function() {
                $('[name="update_cart"]').trigger('click');
            }, 500);
        });
    });
    </script>
    <?php
}

// 添加购物车页面的折扣提示样式
add_action('wp_head', 'add_cart_discount_styles');
function add_cart_discount_styles() {
    if (!is_cart() && !is_checkout()) return;
    ?>
    <style>
        .cart-discount-info {
            font-size: 0.9em;
            color: #28a745;
            margin-top: 5px;
            padding: 3px 8px;
            background: #e8f5e9;
            border-radius: 3px;
            display: inline-block;
        }
        
        .cart-discount-notice {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            border-left: 4px solid #28a745;
        }
        
        .cart-discount-notice h4 {
            margin: 0 0 10px 0;
            color: #333;
        }
        
        .cart-discount-notice table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        
        .cart-discount-notice th,
        .cart-discount-notice td {
            padding: 8px;
            border: 1px solid #ddd;
            text-align: center;
        }
        
        .cart-discount-notice th {
            background: #f0f0f0;
        }
        
        @media (max-width: 768px) {
            .cart-discount-notice {
                font-size: 14px;
                padding: 10px;
            }
        }
    </style>
    <?php
}

// 在购物车页面顶部显示折扣规则提示
add_action('woocommerce_before_cart', 'display_cart_discount_notice');
function display_cart_discount_notice() {
    $rules = get_quantity_discount_rules();
    if (empty($rules)) return;
    
    echo '<div class="cart-discount-notice">';
    echo '<h4>Volume Discount Available</h4>';
    echo '<p>Save more with our bulk pricing:</p>';
    echo '<table>';
    echo '<tr><th>Order Quantity</th><th>Discount</th></tr>';
    
    foreach ($rules as $rule) {
        $discount_percentage = 100 - ($rule['discount'] * 100);
        echo '<tr>';
        echo '<td>' . esc_html($rule['label']) . '</td>';
        echo '<td>' . number_format($discount_percentage, 1) . '% OFF</td>';
        echo '</tr>';
    }
    
    echo '</table>';
    echo '</div>';
}

// 在结算页面显示折扣信息
add_action('woocommerce_review_order_before_cart_contents', 'display_checkout_discount_notice');
function display_checkout_discount_notice() {
    echo '<tr class="checkout-discount-notice">';
    echo '<td colspan="2">';
    echo '<div class="checkout-discount-info">';
    echo 'Volume discounts have been automatically applied to eligible items';
    echo '</div>';
    echo '</td>';
    echo '</tr>';
}

// Mini Cart 更新
add_filter('woocommerce_cart_item_price', 'update_cart_item_price_display', 10, 3);
function update_cart_item_price_display($price, $cart_item, $cart_item_key) {
    // 获取购物车中商品的数量
    $quantity = $cart_item['quantity'];
    
    // 获取商品对象
    $product = $cart_item['data'];
    
    // 获取产品的促销价格(如果存在)
    $sale_price = $product->get_sale_price();
    $regular_price = $product->get_regular_price();
    
    // 如果存在促销价格,使用促销价格进行计算
    $price_to_apply = $sale_price ? $sale_price : $regular_price;

    // 获取适用的折扣
    $discount = get_discount_for_quantity($quantity);

    // 根据折扣计算新的价格
    $discounted_price = $price_to_apply * $discount;

    // 返回格式化的折扣后价格
    return sprintf(
        '<span class="woocs_special_price_code"><span class="woocommerce-Price-amount amount"><bdi>%s<span class="woocommerce-Price-currencySymbol">$</span></bdi></span></span>',
        number_format($discounted_price, 2)
    );
}


// 添加Ajax数量更新支持
add_action('wp_ajax_update_cart_item_discount', 'ajax_update_cart_item_discount');
add_action('wp_ajax_nopriv_update_cart_item_discount', 'ajax_update_cart_item_discount');
function ajax_update_cart_item_discount() {
    $quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 0;
    $product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
    
    if ($quantity && $product_id) {
        $product = wc_get_product($product_id);
        $discount = get_discount_for_quantity($quantity);
        $discounted_price = $product->get_regular_price() * $discount;
        
        wp_send_json_success(array(
            'price' => wc_price($discounted_price),
            'discount' => number_format((1 - $discount) * 100, 1)
        ));
    }
    
    wp_send_json_error();
}   

By 行政