I am try add a filter on woo commerce category view, to order products by discount percent.
I found and adding this nice code from internet, for function.php:
add_filter( 'woocommerce_get_catalog_ordering_args', 'wcs_get_catalog_ordering_args' );
function wcs_get_catalog_ordering_args( $args ) {
$orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
if ( 'on_sale' == $orderby_value ) {
$args['orderby'] = 'meta_value_num';
$args['order'] = 'DESC';
$args['meta_key'] = '_sale_price';
}
return $args;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'wcs_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'wcs_catalog_orderby' );
function wcs_catalog_orderby( $sortby ) {
$sortby['on_sale'] = 'Sort by on sale';
return $sortby;
}
The code works, but not quite as I would like.
Products with discounts are displayed first, but by price, not by discount percentage.
Can we modify the above code to somehow calculate the discount percentage and change the product sorting?
I tried to modify the code, by my self, to calculate the discount percentage
Hector Solutions is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.