Hiển thị phần trăm giảm giá trong WordPress và Woocommerce

Để hiển thị phần trăm giảm giá sản phẩm trong WordPress và Woocommerce, bạn sử dụng đoạn code sau:

function woocommerce_custom_sale_savings() {
   global $product;
   if ( ! $product->is_on_sale() ) return;
   if ( $product->is_type( 'simple' ) ) {
      $max_percentage = ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100;
   } elseif ( $product->is_type( 'variable' ) ) {
      $max_percentage = 0;
      foreach ( $product->get_children() as $child_id ) {
         $variation = wc_get_product( $child_id );
         $price = $variation->get_regular_price();
         $sale = $variation->get_sale_price();
         if ( $price != 0 && ! empty( $sale ) ) $percentage = ( $price - $sale ) / $price * 100;
         if ( $percentage > $max_percentage ) {
            $max_percentage = $percentage;
         }
      }
   }
   if ( $max_percentage > 0 ) {
     return  '<span class="onsale">-' . round($max_percentage) . '%</span>';
   } 
    }

add_filter('woocommerce_sale_flash', 'woocommerce_custom_sale_savings', 10, 3);

Để chỉnh sửa CSS của thành phần này, bạn thao tác CSS đối với 2 class sau:

  • Class .woocommerce ul .products li .product .onsale để chỉnh vị trí
  • Class .woocommerce span.onsale để chỉnh thuộc tính của chữ

Bạn có thể tham khảo đoạn code CSS ví dụ của mình bên dưới

.woocommerce ul.products li.product .onsale{
    left:0;
    right:auto;
    margin:0;
}
.woocommerce span.onsale{
    width:50px;
    border-radius:0;
    background-color:red;
    font-size:12px;
}

Thành phẩm sẽ như thế này:

Chúc bạn thực hiện thành công thao tác hiển thị phần trăm giảm giá trong WordPress và Woocommerce. Hẹn gặp lại bạn trong các bài viết tiếp theo của No Code Building.

 

0989 333 069
Chat Zalo