Sorting products from the oldest to the most recent

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.

How to do it…

We'll need to add two pieces of custom code. The first piece of code will add an option to the sorting drop-down.

  1. Add the following code at the bottom of your theme's 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.

    How to do it…

    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.

  2. Add the following code beneath the code you pasted in the preceding step:
    // 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; 
    }
  3. Save the file and upload it to your site.

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.

How it works...

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.

There's more…

In the code we pasted in, you'll notice the $args array with two keys: orderby and order. A developer can change the values in that array to implement any custom sort order.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset