P
P
PM2018-06-01 17:10:50
WordPress
PM, 2018-06-01 17:10:50

How to sort products by attributes?

Good day!
Tell me what's wrong?
There are products with the attribute "Distance" (value in numbers). You need to add sorting by this attribute.
In functions.php I put this:

/**
 *  Определяем критерии для сортировки с опциями, определенными в методе ниже
 */
add_filter('woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args');

function custom_woocommerce_get_catalog_ordering_args( $args ) {
    global $wp_query;
        // Меняем $_SESSION на $_GET
    if (isset($_GET['orderby'])) {
        switch ($_GET['orderby']) :
            case 'pa_distance' :
                $args['order'] = 'ASC';
                $args['meta_key'] = 'pa_distance';
                $args['orderby'] = 'meta_value_num';
            break;
        endswitch;
    }
    return $args;
}

/**
 *  Добавляем способ сортировки в выпадающий список
 */
add_filter('woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby');

function custom_woocommerce_catalog_orderby( $sortby ) {
    $sortby['pa_distance'] = 'Сортировка по расстоянию от центра';
    return $sortby;
}

/**
 *  Сохраняем атрибуты товара в виде мета данных к записи для того, чтобы использовать их в сортировке и поиске
 */
add_action( 'save_post', 'save_woocommerce_attr_to_meta' );
function save_woocommerce_attr_to_meta( $post_id ) {
        // Получаем названия атрибутов .. Для каждого элемента получаем индекс и название атрибута
        // Затем используем индекс для получения соответствующего отправленного значения из массива attribute_values.
    foreach( $_REQUEST['attribute_names'] as $index => $value ) {
        update_post_meta( $post_id, $value, $_REQUEST['attribute_values'][$index] );
    }
}

In the sort drop-down list, a new item appears, but when it is selected, no products are found - "No products were found matching your query."
I will be very grateful for your help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pychev Anatoly, 2018-06-01
@jimmykoks

In order to use attributes for sorting, they must be stored as metadata. Read here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question