wp wc php sort products archive cheapest price

You can use the following code to sort products in your WordPress/WooCommerce website’s archive page by the cheapest price:

add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args' );
add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby' );
function custom_woocommerce_get_catalog_ordering_args( $args ) {
    $args['orderby'] = 'meta_value_num';
    $args['order'] = 'ASC';
    $args['meta_key'] = '_price';
    return $args;
}
function custom_woocommerce_catalog_orderby( $sortby ) {
    $sortby['price'] = 'Sort by price: low to high';
    return $sortby;
}

Explanation: 1. This code hooks into the woocommerce_get_catalog_ordering_args filter to modify the catalog ordering arguments. 2. It hooks into the woocommerce_default_catalog_orderby_options filter and the woocommerce_catalog_orderby filter to add a new sorting option for price. 3. The custom_woocommerce_get_catalog_ordering_args function sets the ordering parameters to sort by the meta value (price) in ascending order. 4. The custom_woocommerce_catalog_orderby function adds the new sorting option "Sort by price: low to high" to the catalog ordering options.

By adding this code to your theme's functions.php file, you can enable sorting products in the archive page by the cheapest price.