WooCommerce sort products by the actual product width(not the shipping width)

select_width.png

I have regular/simple products and products with variance in the database. Regular products and variations have a product width(_pm_width_inches) associated with them . I am trying to sort based the width and i see that the sorting is yielding random results instead of ascending or descending.

About the meta_key=”_pm_width_inches” , it’s values are stored with double quotes eg:- 12″,also upon selecting all for few post_id it’s value is empty the reson being it’s the parent post_id of a variance.I hereby attach a screenshot(select_width.png).

Here is the code that i’m using :-
add_filter( ‘woocommerce_get_catalog_ordering_args’, ‘sort_by_width_woocommerce_shop’ );

function sort_by_width_woocommerce_shop( $args ) {
global $wp_query;

$orderby_value = isset( $_GET['orderby'] ) ? wc_clean( (string) wp_unslash( $_GET['orderby'] ) ) : wc_clean( get_query_var( 'orderby' ) );

if ( 'width-asc' == $orderby_value ) {
    $args['orderby'] = 'meta_value_num';
    $args['order'] = 'ASC';
    $args['meta_key'] = '_pm_width_inches';
}
else if('width-desc'== $orderby_value){
    $args['orderby'] = 'meta_value_num';
    $args['order'] = 'DESC';
    $args['meta_key'] = '_pm_width_inches';

}

/* ?>
“. var_dump( $args[‘meta_key’] ).””;?>

return $args;

}

// 2. Add new product filter to Sorting dropdown

add_filter( ‘woocommerce_catalog_orderby’, ‘custom_woocommerce_catalog_orderby’ );
function custom_woocommerce_catalog_orderby( $orderby ) {

unset($orderby);
$orderby['price'] = __('Price: Low to High');
$orderby['price-desc'] = __('Price: High to Low');
$orderby['popularity'] = __('By Popularity');
$orderby['date'] = __('Newest Arrivals');
$orderby['width-asc'] = __('Width: small to large');
$orderby['width-desc'] = _('Width:large to  small ');

/* ?>
“.var_dump($orderby).””;?>

Read more here:: WooCommerce sort products by the actual product width(not the shipping width)

Leave a Reply

Your email address will not be published. Required fields are marked *