admin管理员组文章数量:1326277
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 badges2 Answers
Reset to default 0No, 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.
本文标签: Custom WP Query order function possible
版权声明:本文标题:Custom WP Query order function possible? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742211865a2433857.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论