最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Custom WP Query order function possible?

programmeradmin5浏览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?

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?

Share Improve this question asked Aug 4, 2020 at 13:55 RunnickRunnick 1,0593 gold badges14 silver badges26 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 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.

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.

发布评论

评论列表(0)

  1. 暂无评论