WordPress 一次通过 2 个自定义字段订购帖子 [英] WordPress order posts by 2 custom fields at once
问题描述
我想在同一个调用中按 2 个自定义字段对帖子进行排序.这怎么可能?
此下一个代码订购成功,但仅限于 1 NUMBER 个自定义字段(不是 STRING):
This next code order successfully, but only by only 1 NUMBER custom field (not STRING):
add_action('pre_get_posts', function ($q) {
if (
!is_admin() // Target only front end queries
&& $q->is_main_query() // Target the main query only
&& ($q->is_search() || $q->is_post_type_archive('data-base'))
) {
$q->set('meta_key', 'custom_field_1');
$q->set('order', 'DESC');
$q->set('orderby', 'meta_value');
}
});
<小时>
更新 1:
目前@Mohammed Yassine CHABLI 的第一个答案有效,但它不是按 number
排序,而是按 String
排序.这意味着81"会在9"之前出现,这并不好.有什么解决办法吗?
Currently @Mohammed Yassine CHABLI's first answer works, but it doesn't sort by number
, but by String
. That means that "81" will come before "9", which is not good. Any solution for that?
可能有帮助的资源:
使用woocommerce在自定义排序中添加meta_type>
推荐答案
您需要 WP 方式在 ORDER BY
中提供表达式;
You need the WP way of providing an expression in the ORDER BY
;
ORDER BY 0 + meta_key
也就是对meta_key做一些事情,把它转换成数值.
That is, do something to meta_key to convert it into a numeric value.
这篇关于WordPress 一次通过 2 个自定义字段订购帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!