php - WooCommerce how to display "you save X%" on checkout page
问题描述
I have made a function that displays on checkout the total savings based on product discounts but I would like it to show the percentage saved above the order total, and if possible show it inside of a box.
Code:
function wc_discount_total() {
global $woocommerce;
$discount_total = 0;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
if ( $_product->is_on_sale() ) {
$regular_price = $_product->get_regular_price();
$sale_price = $_product->get_sale_price();
$discount = ($regular_price - $sale_price) * $values['quantity'];
$discount_total += $discount;
}
}
if ( $discount_total > 0 ) {
echo '<tr class="cart-discount">
<th>'. __( 'Your Savings', 'woocommerce' ) .'</th>
<td data-title=" '. __( 'You Saved', 'woocommerce' ) .' ">'
. wc_price( $discount_total + $woocommerce->cart->discount_cart ) .'</td>
</tr>';
}
}
add_action( 'woocommerce_cart_totals_after_order_total', 'wc_discount_total', 99);
add_action( 'woocommerce_review_order_after_order_total', 'wc_discount_total', 99);
How my current checkout looks like:
Zoomed:
How I would like it to look:
解决方案
If there is a discount on that order, then you could add another table row tag and calculate the percentage. So it'd be something like this:
add_action('woocommerce_cart_totals_after_order_total', 'wc_discount_total', 99);
add_action('woocommerce_review_order_after_order_total', 'wc_discount_total', 99);
function wc_discount_total()
{
global $woocommerce;
$discount_total = 0;
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
if ($_product->is_on_sale()) {
$regular_price = $_product->get_regular_price();
$sale_price = $_product->get_sale_price();
$discount = ($regular_price - $sale_price) * $values['quantity'];
$discount_total += $discount;
}
}
if ($discount_total > 0) {
echo '<tr class="cart-discount">
<th>' . __('Your Savings', 'woocommerce') . '</th>
<td data-title=" ' . __('You Saved', 'woocommerce') . ' ">'
. wc_price($discount_total + $woocommerce->cart->discount_cart) . '</td>
</tr>';
$total = WC()->cart->cart_contents_total;
$total_saved = wc_price($discount_total + $woocommerce->cart->discount_cart);
$percentage_saved = round(($total_saved * 100) / $total);
echo '<tr class="cart-percentage-discount">
<th>' . __('Percentage Saved', 'woocommerce') . '</th>
<td data-title=" ' . __('You Saved', 'woocommerce') . ' ">' . esc_html($percentage_saved . "%") . '</td>
</tr>';
}
}
推荐阅读
- javascript - JS/jQuery - 第一次点击会忽略第一个动画,其他每次点击都可以正常工作
- regex - bash 查找和替换 - sed awk
- java - 为了使用 Java 提交表单,使用表格中的输入框的最佳方法是什么?
- scala - 错误:对象 rocksdb 不是包 orgs 的成员
- python - sklearn 的线性判别分析
- regex - Notepad++ 如何自定义正则表达式这个内容
- reactjs - 如何更新反应变量状态?
- asynchronous - 使用 Redux 的异步等待似乎不起作用
- c++ - 利用输入文件(字符串和整数)中的数据并在循环中利用
- wordpress - 联系表格 7 多步骤 wordpress 该网站遇到技术困难