워드프레스 젯리스팅 할인율 숏코드 생성 스니펫

워드프레스 젯리스팅 할인율 숏코드 생성 스니펫

add_shortcode( 'sale_percentage', function( $atts ) {
    $atts = shortcode_atts( array(
        'id' => get_the_ID(),
    ), $atts, 'sale_percentage' );
    $product = wc_get_product( $atts['id'] );
    if ( ! $product ) return '';
    $max_percentage = 0;
    // 옵션상품인 경우
    if ( $product->is_type('variable') ) {
        foreach ( $product->get_children() as $child_id ) {
            $variation = wc_get_product( $child_id );
            if ( $variation && $variation->is_on_sale() ) {
                $regular_price = (float) $variation->get_regular_price();
                $sale_price    = (float) $variation->get_sale_price();
                if ( $regular_price > 0 && $sale_price > 0 ) {
                    $percentage = round( ( ($regular_price - $sale_price) / $regular_price ) * 100 );
                    if ( $percentage > $max_percentage ) {
                        $max_percentage = $percentage;
                    }
                }
            }
        }
    }
    // 단순 상품인 경우 
    else {
        if ( $product->is_on_sale() ) {
            $regular_price = (float) $product->get_regular_price();
            $sale_price    = (float) $product->get_sale_price();
            if ( $regular_price > 0 && $sale_price > 0 ) {
                $max_percentage = round( ( ($regular_price - $sale_price) / $regular_price ) * 100 );
            }
        }
    }
    return $max_percentage > 0 ? $max_percentage . '%' : '';
});

Use dynamic field 추가 후 Post ID -> custom field output [sale_percentage id=”%s”]

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다