If the preceding recipe doesn't give you enough options to sort your products, you can add custom code to meet your needs. With a bit of code, you can sort products from the oldest to the most recent.
We'll need to add two pieces of custom code. The first piece of code will add an option to the sorting drop-down.
functions.php
file under wp-content/themes/your-theme-name/
or in your custom WooCommerce plugin:// Add a new sorting option add_filter( 'woocommerce_default_catalog_orderby_options', 'woocommerce_cookbook_catalog_orderby' ); add_filter( 'woocommerce_catalog_orderby', 'woocommerce_cookbook_catalog_orderby' ); function woocommerce_cookbook_catalog_orderby( $sortby ) { $sortby['oldest_to_newest'] = __( 'Sort by oldest to newest', 'woocommerce' ); return $sortby; }
This code should add a new option to the sorting drop-down.
Unfortunately, WooCommerce doesn't know what to do with that value. We still need to add a bit more code to tell WooCommerce exactly how to process that information.
// Add sorting oldest to newest functionality to sorting dropdown add_filter( 'woocommerce_get_catalog_ordering_args', 'woocommerce_cookbook_get_catalog_ordering_args' ); function woocommerce_cookbook_get_catalog_ordering_args( $args ) { // get the orderby value $orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) ); // if the orderby value matches our custom option if ( 'oldest_to_newest' == $orderby_value ) { $args['orderby'] = 'date'; $args['order'] = 'ASC'; } return $args; }
Now, if you click on the new option, which we created in the preceding code from the sorting drop-down, the page will reload and the items will be rearranged according to the new order.
The actual functionality happens in the woocommerce_cookbook_get_catalog_ordering_args
function. In there, we determine the $orderby_value
, which is basically checking which option is set in the drop-down. After we have the value selected, we check whether that's our custom option. If it is our custom option, then we change the sort order.