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ì?
-
Cách 1: Thêm hook vào functions.php
Bạn chỉ cần thêm đoạn code sau vào file functions.php của theme trang sử dụng là được nhé123456789101112131415161718192021222324/** Thay chữ sale bằng phần trăm giảm giá*/add_filter('woocommerce_sale_flash','devvn_woocommerce_sale_flash', 10, 3);function devvn_woocommerce_sale_flash($text, $post, $product){ob_start();$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( 'devvn_woocommerce_sale_flash', '-' . $sale . '%', $post, $product );endif;return ob_get_clean();} -
Cách 2: Thay đổi bằng file templates
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:
12345678910111213141516171819202122232425262728/*** Thay chữ sale bằng phần trăm giảm giá*/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', '-' . $sale . '%', $post, $product );endif;endif;
Chúc các bạn thành công ^^
Nguồn: levantoan[.]com










