2 years ago

#28481

test-img

Vladimir Kyatipov

WooCommerce sort by percentage discount amount in woo shortcode

I want to make custom sort option and use it into shortcode. i want to make custom sort by percent discont for sale products. Here is my code:

add_action('woocommerce_process_product_meta', 'woo_calc_my_discount');
function woo_calc_my_discount( $product_id ) {

$_product = wc_get_product( $product_id );

$regular = (float) $_product->get_regular_price();

$sale = (float) $_product->get_sale_price();

$discount = round( 100 - ( $sale / $regular * 100), 2 );

update_post_meta( $product_id, '_discount_amount', $discount );

}

add_action('woocommerce_product_quick_edit_save', 'sv_woo_calc_my_discount_quickedit');
function sv_woo_calc_my_discount_quickedit( $post ) {

$_product = wc_get_product( $post );

$regular = (float) $_product->get_regular_price();

$sale = (float) $_product->get_sale_price();

$discount = round( 100 - ( $sale / $regular * 100), 2 );

update_post_meta( $_product->get_id(), '_discount_amount', $discount );

}


add_filter( 'woocommerce_get_catalog_ordering_args', 'misha_custom_product_sorting' );
 
function misha_custom_product_sorting( $args ) {

    // Discount percentage: High to Low
    if( isset( $_GET['orderby'] ) && '_discount_amount' === $_GET['orderby'] ) {
        $args['meta_key'] = '_discount_amount';
        $args['order'] = 'desc';
    }
    return $args;
 
}


add_filter( 'woocommerce_catalog_orderby', 'misha_add_custom_sorting_options' );
 
function misha_add_custom_sorting_options( $options ){
    $options['_discount_amount'] = 'Sale: High to Low';
    return $options;
}

I use also:

[products on_sale="true" orderby="_discount_amount"]

but seems it's without success for now.. Any ideas? thanks!

php

wordpress

woocommerce

hook-woocommerce

woocommerce-theming

0 Answers

Your Answer

Accepted video resources