programing

Woocommerce 3의 판매 배지에 할인율을 표시합니다.

coolbiz 2023. 3. 15. 23:21
반응형

Woocommerce 3의 판매 배지에 할인율을 표시합니다.

이것은 단순한 제품에서는 작동하지만 가변 제품에서는 두 가지 오류가 발생합니다.아카이브의 판매 플래시에 "숫자가 아닌 값이 발견되었습니다"라는 오류와 함께 NAN%가 표시됩니다.

내 코드:

add_filter( 'woocommerce_sale_flash', 'add_percentage_to_sale_bubble' );
function add_percentage_to_sale_bubble( $html ) {
    global $product;
    $percentage = round( ( ( $product->regular_price - $product->sale_price ) / $product->regular_price ) * 100 );
    $output ='<span class="onsale">SALE<br>-'.$percentage.'%</span>';
    return $output;
}

어떻게 고칠지 생각나는 거 없어?

어떤 도움이라도 대단히 감사합니다.

2020년 업데이트 - 코드그룹화된 제품 취급을 재검토하였습니다.

사용하고 있는 코드는 Woocommerce 3 이후 오래된 코드입니다.대신 가변 제품(및 그룹화된 제품)을 처리하는 다음 작업을 시도하십시오.

add_filter( 'woocommerce_sale_flash', 'add_percentage_to_sale_badge', 20, 3 );
function add_percentage_to_sale_badge( $html, $post, $product ) {

  if( $product->is_type('variable')){
      $percentages = array();

      // Get all variation prices
      $prices = $product->get_variation_prices();

      // Loop through variation prices
      foreach( $prices['price'] as $key => $price ){
          // Only on sale variations
          if( $prices['regular_price'][$key] !== $price ){
              // Calculate and set in the array the percentage for each variation on sale
              $percentages[] = round( 100 - ( floatval($prices['sale_price'][$key]) / floatval($prices['regular_price'][$key]) * 100 ) );
          }
      }
      // We keep the highest value
      $percentage = max($percentages) . '%';

  } elseif( $product->is_type('grouped') ){
      $percentages = array();

      // Get all variation prices
      $children_ids = $product->get_children();

      // Loop through variation prices
      foreach( $children_ids as $child_id ){
          $child_product = wc_get_product($child_id);

          $regular_price = (float) $child_product->get_regular_price();
          $sale_price    = (float) $child_product->get_sale_price();

          if ( $sale_price != 0 || ! empty($sale_price) ) {
              // Calculate and set in the array the percentage for each child on sale
              $percentages[] = round(100 - ($sale_price / $regular_price * 100));
          }
      }
      // We keep the highest value
      $percentage = max($percentages) . '%';

  } else {
      $regular_price = (float) $product->get_regular_price();
      $sale_price    = (float) $product->get_sale_price();

      if ( $sale_price != 0 || ! empty($sale_price) ) {
          $percentage    = round(100 - ($sale_price / $regular_price * 100)) . '%';
      } else {
          return $html;
      }
  }
  return '<span class="onsale">' . esc_html__( 'SALE', 'woocommerce' ) . ' ' . $percentage . '</span>';
}

코드는 기능합니다.php 파일(또는 활성 테마)입니다(또는 활성 테마)을 입력합니다.테스트 및 동작.

언급URL : https://stackoverflow.com/questions/52558950/display-the-discount-percentage-on-the-sale-badge-in-woocommerce-3

반응형