I'm trying to order products by on sale first and regular priced products second. Both have to be sorted alphabetically in ascending order.
On the website the on sale products are first but they are not alphabetical and there is some regular priced products at the end of the category that are not alphabetical.
Here is the code I'm using.
// adding option ' Sort by on sale ' to sorting dropdown menu
add_filter( 'woocommerce_default_catalog_orderby_options', amt_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'amt_catalog_orderby' );
function amt_catalog_orderby( $sortby ) {
$sortby['on_sale'] = 'Sort by on sale';
return $sortby;
}
/**
* return default ordering of the products in catalog by 'on_sale'
**/
add_filter('woocommerce_default_catalog_orderby', amt_default_catalog_orderby');
function amt_default_catalog_orderby() {
// die('default sorting');
return 'on_sale';
}
/**
* WooCommerce Sales Sorting Filter
*/
add_filter( 'woocommerce_get_catalog_ordering_args', 'amt_get_catalog_ordering_args' );
function amt_get_catalog_ordering_args( $args ) {
$orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
if ( 'on_sale' == $orderby_value ) {
$current_category = get_queried_object();
// var_dump($current_category);
add_action( 'woocommerce_product_query', 'amt_on_sale_query' );
function amt_on_sale_query( $q ){
$meta_query = $q->get( 'meta_query' );
$meta_query = array(
'relation' => 'OR',
array(
'key' => '_sale_price',
'compare' => 'NOT EXISTS'
),
array(
'relation' => 'OR',
array(
'key' => '_sale_price',
'value' => '',
'compare' => "="
// 'value'=>array(''),
// 'compare' => 'IN'
),
array(
'key' => '_sale_price',
'value'=>0,
'compare' => '>=',
'type' => 'numeric',
)
),
);
$q->set('meta_query', $meta_query );
$q->set('orderby', array( 'meta_value' => 'DESC', 'title' => 'ASC' ));
}
}
}