1

I am trying to create a custom query to order the posts by the sum of the values for the '_heateor_sss_shares_meta' key in the postmeta table. A sample of the values that I am working with is:

a:5:{s:8:"facebook";i:0;s:7:"twitter";i:0;s:6:"reddit";i:0;s:8:"linkedin";i:0;s:9:"pinterest";i:1;}

What I understand that I should do to get the sum of the values for that record is:

$share_counts = get_post_meta( $post_id, '_heateor_sss_shares_meta', true );

The WP_Query code that I need to amend with the orderby is:

$args=array(
    'post_type' => "listing",
    'post_status' => 'publish',
    'posts_per_page' => $number_posts,
);

What I can gather is that I need to add:

'meta_key' => '_heateor_sss_shares_meta',
'orderby' => 'meta_value_num',     <<<<<<<<<<<<<<< I don't know what should go here to do the calculation
'order' => 'DESC'

My question is, how can I do a sum calculation on the value of the '_heateor_sss_shares_meta' key so that I can order by the highest to the lowest?

user857629
  • 33
  • 4
  • Maybe this post will help you: https://wordpress.stackexchange.com/questions/237610/how-to-get-sum-of-meta-values-of-a-meta-key-in-wp-query-according-to-conditions – Bernhard Beatus May 28 '21 at 17:00
  • Thanks for the link. Well, it does a sum of the values, but there is no sorting involved. What I understand this would do is to query all records then a calculation is done on each record for the one field. There is no filtering or ordering. I would then have to put everything in an array and sort it, then do a new query to get all the posts that are in the top X number. That is a lot of overhead. I would hope that there is a more elegant way. – user857629 May 28 '21 at 18:38
  • I think thats the only possible solution. Sorry – Bernhard Beatus May 29 '21 at 14:30

0 Answers0