0

I have a plugin that has a meta field that keeps shares for the post in array format:

["facebook" => 12, "pinterest" => 12]

I would like to get 3 most shared posts (by all shares combined) in custom WP Query, but not sure how to it as it only allows to provide meta filed and value, but not the function?

Is it possible to have custom sorting function there?

2 Answers 2

0

No, it's not possible. You can't actually store arrays as meta. When they're saved they're converted to a string, so there aren't individual parts that you can sort by. To do this you will need to store the share numbers as their own keys.

1
  • Yes, so my idea was to pull the numbers in php, combine them and sort of the fly afterwards. So you're saying only MySQL is possible for that kind of sorting?
    – Runnick
    Aug 4, 2020 at 14:25
0

The most sensible way to achieve what you want that I'm aware of is to write your own code which puts the data you want in a single new meta value which you can then easily work with in WP_Query.

This is rough code, but you should be able to see how it works and modify it to do what you want.

function map_my_array_metavalue($postID) {

    $arrayValue = get_post_meta($postId, "plugin_meta_key") ; // change plugin_meta_key to whatever it is

    $newValue = $arrayValue['facebook'] + $arrayValue['pinterest'] ; 

    update_post_meta($postId, "combined_share_count", $newValue) ;

}

add_action('save_post', 'map_my_array_metavalue', 10, 1);

Now you can write simple WP_Query arguments using the meta key 'map_my_array_metavalue'.

Obviously this example only works whenever a post is saved so you may need to figure out a more sensible place to hook this code into. If it doesn't happen too often, probably you can hook somehow into when the plugin recording this data updates it.

Note:

You also have the problem of initialising this data for all posts that don't have it yet. You could for example do a one time run of the above code for all post ID's.

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.