product sorting by custom attributes and custom query

I am try to sort product by custom attribute and custom query

Currently I am using below code but it is not return desired result.

add_filter('woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args');

function custom_woocommerce_get_catalog_ordering_args($args) {
    global $wp_query;
    if (isset($_GET['orderby'])) {
        switch ($_GET['orderby']):
    case 'pa_capacity':
        $args['order'] = 'ASC';
        $args['meta_key'] = 'pa_capacity';
        $args['orderby'] = 'meta_value_num';
        break;
        endswitch;
    }
    return $args;
}

add_filter('woocommerce_catalog_orderby', 'custom_woocommerce_capacity_orderby');

function custom_woocommerce_capacity_orderby($sortby) {
    $sortby['pa_capacity'] = 'Sort by Capacity: low to high';
    return $sortby;
}

below query working for desired result

$cat_id = $_GET['cat_id'];
asort($capacity_list, SORT_NUMERIC);
$catStr = implode(',', array_keys($capacity_list));

$queryStrc = "SELECT js_posts.*
FROM js_posts
LEFT JOIN js_term_relationships ON (js_posts.ID = js_term_relationships.object_id)
LEFT JOIN js_terms ON (js_term_relationships.term_taxonomy_id = js_terms.term_id)
WHERE 1=1 AND (js_term_relationships.term_taxonomy_id IN (" . $catStr . ")) AND js_posts.post_type = 'product' AND (js_posts.post_status = 'publish' OR js_posts.post_status = 'private')
AND js_posts.id IN(
    SELECT js_posts.id
    FROM js_posts
    LEFT JOIN js_term_relationships ON (js_posts.ID = js_term_relationships.object_id)
    INNER JOIN js_postmeta ON (js_posts.ID = js_postmeta.post_id)
    INNER JOIN js_terms ON (js_term_relationships.term_taxonomy_id = js_terms.term_id)
    WHERE 1=1 AND (js_term_relationships.term_taxonomy_id IN (" . $cat_id . ")) AND ((js_postmeta.meta_key = '_visibility' AND js_postmeta.meta_value IN ('visible','catalog'))) AND js_posts.post_type = 'product' AND (js_posts.post_status = 'publish')
    GROUP BY js_posts.ID
    ORDER BY js_posts.menu_order ASC, js_posts.post_title ASC
)
GROUP BY js_posts.ID
ORDER BY CAST(js_terms.name AS DECIMAL) ASC";
$pageposts = $wpdb->get_results($queryStrc, OBJECT);

so how can I use above code for product sorting?

Read more here: product sorting by custom attributes and custom query

Leave a Reply

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