Created
May 31, 2023 08:47
-
-
Save jmcausing/3172104e28cca6fd5329d6f6c73a4663 to your computer and use it in GitHub Desktop.
WooCommerce - Add additional sorting by sales (ASC) - exclude out of stock
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Add sorting option to sort products by sales (ASC) on the shop page | |
function add_custom_product_sorting_option( $options ) { | |
$options['sales_asc'] = __( 'Sort by Sales (ASC)', 'text-domain' ); | |
return $options; | |
} | |
add_filter( 'woocommerce_get_catalog_ordering_args', 'add_custom_product_sorting_option' ); | |
// Define sorting option arguments for sorting by sales (ASC) and excluding out-of-stock products | |
function set_custom_product_sorting_option( $sort_args ) { | |
if ( isset( $_GET['orderby'] ) && 'sales_asc' === $_GET['orderby'] ) { | |
$sort_args['orderby'] = 'meta_value_num'; | |
$sort_args['order'] = 'ASC'; | |
$sort_args['meta_key'] = 'total_sales'; // Change this if you have a different meta key for sales | |
$sort_args['meta_query'] = array( | |
array( | |
'key' => '_stock_status', | |
'value' => 'outofstock', | |
'compare' => 'NOT EXISTS', | |
), | |
); | |
} | |
return $sort_args; | |
} | |
add_filter( 'woocommerce_get_catalog_ordering_args', 'set_custom_product_sorting_option' ); | |
// Modify the sorting options dropdown label | |
function modify_product_sorting_options( $sorting_options ) { | |
$sorting_options['sales_asc'] = __( 'Sort by Sales (ASC)', 'text-domain' ); | |
return $sorting_options; | |
} | |
add_filter( 'woocommerce_catalog_orderby', 'modify_product_sorting_options' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment