Bạn là chủ shop bán hàng online trên website bạn muốn thay đổi chữ “Sale” thành “%” giảm giá để chạy trương trình thu hút được khách hàng hơn, vậy làm gì để thay đổi ?
Bài viết này dành cho bạn kể cả code có thể khảo?

Thay chữ sale bằng phần trăm giảm giá trong woocommerce
Bạn chỉ cần copy đoạn code dưới đây vào trong file function.php rồi xem kết quả
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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
add_filter('woocommerce_sale_flash', 'hwp_woocommerce_sale_flash', 10, 3); function hwp_woocommerce_sale_flash($html, $post, $product){ return '<span class="onsale"><span>' . hwp_presentage_bubble($product) . '</span></span>'; } function hwp_presentage_bubble( $product ) { $post_id = $product->get_id(); if ( $product->is_type( 'simple' ) || $product->is_type( 'external' ) ) { $regular_price = $product->get_regular_price(); $sale_price = $product->get_sale_price(); $bubble_content = round( ( ( floatval( $regular_price ) - floatval( $sale_price ) ) / floatval( $regular_price ) ) * 100 ); } elseif ( $product->is_type( 'variable' ) ) { if ( $bubble_content = hwp_percentage_get_cache( $post_id ) ) { return hwp_percentage_format( $bubble_content ); } $available_variations = $product->get_available_variations(); $maximumper = 0; for ( $i = 0; $i < count( $available_variations ); ++ $i ) { $variation_id = $available_variations[ $i ]['variation_id']; $variable_product = new WC_Product_Variation( $variation_id ); if ( ! $variable_product->is_on_sale() ) { continue; } $regular_price = $variable_product->get_regular_price(); $sale_price = $variable_product->get_sale_price(); $percentage = round( ( ( floatval( $regular_price ) - floatval( $sale_price ) ) / floatval( $regular_price ) ) * 100 ); if ( $percentage > $maximumper ) { $maximumper = $percentage; } } $bubble_content = sprintf( __( '%s', 'woocommerce' ), $maximumper ); hwp_percentage_set_cache( $post_id, $bubble_content ); } else { $bubble_content = __( 'Sale!', 'woocommerce' ); return $bubble_content; } return hwp_percentage_format( $bubble_content ); } function hwp_percentage_get_cache( $post_id ) { return get_post_meta( $post_id, '_hwp_product_percentage', true ); } function hwp_percentage_set_cache( $post_id, $bubble_content ) { update_post_meta( $post_id, '_hwp_product_percentage', $bubble_content ); } //Định dạng kết quả dạng -{value}%. Ví dụ -20% function hwp_percentage_format( $value ) { return str_replace( '{value}', $value, '-{value}%' ); } // Xóa cache khi sản phẩm hoặc biến thể thay đổi function hwp_percentage_clear( $object ) { $post_id = 'variation' === $object->get_type() ? $object->get_parent_id() : $object->get_id(); delete_post_meta( $post_id, '_hwp_product_percentage' ); } add_action( 'woocommerce_before_product_object_save', 'hwp_percentage_clear' ); |
Chúc A/E thành công!