D
D
Damaks2015-09-18 12:08:11
CMS
Damaks, 2015-09-18 12:08:11

Multi-factor sorting posts in a wp_query loop?

Good afternoon.
Got a question. There is such a construction for displaying posts in a custom taxonomy:

$args = array(
    'post_type' => 'my-custom-type',
    'meta_query' => array(
        'relation' => 'AND',
        array(
            'key' => 'ratings_users',
            'type' => 'NUMERIC',
        ),
        array(
            'key' => 'ratings_average',
            'type' => 'NUMERIC',
        ),
        array(
            'key' => 'views',
            'type' => 'NUMERIC',
        ),
    ),
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
);

$query = new WP_Query(
    array_merge(
        $args,
        $wp_query->query
    )
)

The task is to sort by arbitrary fields as follows:
1) the posts with the highest value of the "ratings_users" field go first;
2) if the "ratings_users" values ​​are the same, then the posts with the highest "ratings_average" field value go first;
3) if the values ​​of both fields are the same or zero, then the sorting goes according to the highest value of the "views" field.
In this example, only sorting by "ratings_users" is in effect, as the first value in the array. The rest do not affect sorting.
How can the function be modified or what other plugin-free methods for implementing multifactor sorting are there?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Vorotnev, 2015-09-19
@HeadOnFire

You need GROUP BY. Read the doc on the posts_groupby hook
https://codex.wordpress.org/Plugin_API/Filter_Refe...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question