I'm storing post meta values _likes and _dislikes in postmeta. In some cases, I want to be able to query for posts by their netto score (likes minus dislikes) and order them by it.

I'm familiar with querying and ordering posts by meta values, but I'm not sure if this particular problem can be solved in pre_get_posts. I get the feeling I need to create a new WP_Query object, but I'd really prefer to not dump the current query object.

Is it possible to alter the already existing query object in the pre_get_posts action to do simple arithmetic operations on meta values?

  • You should be able to use most WP_Query options in pre_get_posts, after all, all you're doing there is just modifying an instance of WP_Query anyway :) Have you checked codex.wordpress.org/Class_Reference/WP_Query to see if you can do it with a meta_query?
    – Tim Malone
    Commented Jun 5, 2016 at 23:20

1 Answer 1


The way you are trying to do it is probably the wrong way.

WP_Query does not have any build in feature to subtract the values from two custom fields and then returning (or ordering) posts according to the value of the subtraction from the two fields. You can probably filter the generated SQL via the posts_clauses filter or the relevant single clauses filters to intoduce a feature like the one you want to.

I will probably not go down that route as complex SQL queries, like the one you need, can become quite expensive and very slow to execute, specially as your db grow. You might want to look at writing a once-off script which will take all posts, calculate the difference between the two custom fields and saving that difference in another (maybe hidden) custom field. As I said, this will be a once of script which you will remove once once done.

It is then just a matter of writing another script which automatically update this third custom field with the difference of the other two when either of the other two custom fields is updated. For this you can look at actions like updated_post_meta (see this answer).

It will then be as easy to query (or order) your posts by this third custom field without any extra filter, actions or other operations

  • I was hoping I could avoid a custom field that is essentially the sum of two other fields, but I think you might be right. Upside is that to get posts ordered by the new field I don't need to change any of my other code. Commented Jun 6, 2016 at 8:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.