Thứ Hai, 21 tháng 5, 2018

Thay chữ Sale bằng % giảm giá trong woocommerce

Nhiều khi chúng ta không muốn hiển thị chữ SALE khi sản phẩm đó có chương trình giảm giá. Mà thay vào đó sẽ hiển thị phần trăm (%) giảm giá của sản phẩm đó. vậy chúng ta sẽ làm gì?

Thay chữ sale bằng phần trăm giảm giá trong woocommerce

Nếu các bạn chưa có file sale-flash.php trong theme thì các bạn làm như sau. Tạo file sale-flash.php trong thư mục [your-theme]/woocommerce/loop/ và [your-theme]/woocommerce/single-product/ với nội dung file sale-flash.php như sau:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
/**
 * Product loop sale flash
 * Edit by levantoan.com
 * This template can be overridden by copying it to yourtheme/woocommerce/loop/sale-flash.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @author        WooThemes
 * @package    WooCommerce/Templates
 * @version     1.6.4
 */
 
if ( ! defined( 'ABSPATH' ) ) {
   exit; // Exit if accessed directly
}
global $post, $product;
if ( $product->is_on_sale() ) :
    if ( ! $product->is_in_stock() ) return;
    $sale_price = get_post_meta( $product->get_id(), '_price', true);
    $regular_price = get_post_meta( $product->get_id(), '_regular_price', true);
    if (empty($regular_price) && $product->is_type( 'variable' )){
        $available_variations = $product->get_available_variations();
        $variation_id = $available_variations[0]['variation_id'];
        $variation = new WC_Product_Variation( $variation_id );
        $regular_price = $variation ->regular_price;
        $sale_price = $variation ->sale_price;
    }
    $sale = ceil(( ($regular_price - $sale_price) / $regular_price ) * 100);
    if ( !empty( $regular_price ) && !empty( $sale_price ) && $regular_price > $sale_price ) :
        $R = floor((255*$sale)/100);
        $G = floor((255*(100-$sale))/100);
        $bg_style = 'background:none;background-color: rgb(' . $R . ',' . $G . ',0);';
        echo apply_filters( 'woocommerce_sale_flash', '<span class="onsale" style="'. $bg_style .'">-' . $sale . '%</span>', $post, $product );
    endif;
endif;
Chúc các bạn thành công ^^
Down load file sale-flash.php
Tham khảo: http://code.tutsplus.com/articles/customize-the-behavior-of-the-woocommerce-sale-flash–cms-22225

Không có nhận xét nào:
Write nhận xét