S
S
santime2018-10-20 20:36:06
WordPress
santime, 2018-10-20 20:36:06

How to sort a selection (WP_Query) by a custom field after processing its value?

The bottom line is that in an arbitrary field I store a serialized array with data about the rating of the record, a simple array of the type:
array(
user_id_1 => number from 1 to 5,
user_id_2 => number from 1 to 5,
)
When the record is displayed, all this is considered and shown the average rating number is from 1 to 5.
The documentation has an example for sorting by a custom field, however, I need to sort not by the value of the field, but by its processed value. Is there something similar in WP?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Igor Vorotnev, 2018-10-21
@santime

If you need to perform such calculations, then you have architecturally incorrectly implemented. Such data should not be stored in postmeta, but in a separate table. Structure, roughly (let's call the table post_ratings):

id  |  post_id  |  user_id  |  rating
-------------------------------------
1   |  189      |  34       |  4

It is for this table that you make an initial selection with a miscalculation of the average rating and sorting, at the output you get a post_id list. You then pass them to WP_Query via the post__in parameter.
Alternatively, you can "cache" the average, already calculated, rating in the postmeta table, as a single int. Recalculate it either every time a new record is added to the custom table (by query or queued), or by cron once in a while.

I
id_baton4eg, 2018-10-21
@id_baton4eg

well, make a variable, count in it, and put a variable in place of the value.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question