How to add a custom sorting or order by option on category archive or product archive page in woocommerce wordpress
Just copy and paste below code into your theme's functions.php or into your custom plugin file and change option name and value according to your requirement.
function rj_add_custom_postmeta_orderby( $sortby ) {
$sortby = array(); // do this for remove all default options
$sortby['grapes'] = __( 'Grapes', 'woocommerce' );
$sortby['main_region'] = __( 'Region', 'woocommerce' );
$sortby['wine_color'] = __( 'Colors', 'woocommerce' );
$sortby['class'] = __( 'Type', 'woocommerce' );
return $sortby;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'rj_add_custom_postmeta_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'rj_add_custom_postmeta_orderby' );
function rj_get_catalog_ordering_args( $sort_args ) {
$orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
switch( $orderby_value ) {
case 'grapes':
case 'main_region':
case 'wine_color':
case 'class':
$sort_args['orderby'] = 'meta_value'; // if you have numeric value for field then you can use meta_value_num
$sort_args['order'] = 'asc'; // asc/desc
$sort_args['meta_key'] = $orderby_value;
break;
}
return $sort_args;
}
add_filter( 'woocommerce_get_catalog_ordering_args', 'rj_get_catalog_ordering_args' );
function rj_add_custom_postmeta_orderby( $sortby ) {
$sortby = array(); // do this for remove all default options
$sortby['grapes'] = __( 'Grapes', 'woocommerce' );
$sortby['main_region'] = __( 'Region', 'woocommerce' );
$sortby['wine_color'] = __( 'Colors', 'woocommerce' );
$sortby['class'] = __( 'Type', 'woocommerce' );
return $sortby;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'rj_add_custom_postmeta_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'rj_add_custom_postmeta_orderby' );
function rj_get_catalog_ordering_args( $sort_args ) {
$orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
switch( $orderby_value ) {
case 'grapes':
case 'main_region':
case 'wine_color':
case 'class':
$sort_args['orderby'] = 'meta_value'; // if you have numeric value for field then you can use meta_value_num
$sort_args['order'] = 'asc'; // asc/desc
$sort_args['meta_key'] = $orderby_value;
break;
}
return $sort_args;
}
add_filter( 'woocommerce_get_catalog_ordering_args', 'rj_get_catalog_ordering_args' );
Comments
Post a Comment