我在自定义帖子类型中有4个文本字段类型,分别是brand_fbn
,model_fbn
,year_fbn
和plate_number
。我希望按brand_fbn
- model_fbn
- year_fbn
- plate_number
对帖子进行排序。但我坚持这一点,
这是我的代码(错误)
$ins = new WP_Query(array(
"post_type" => "application-list",
"author" => $current_user->ID,
"meta_key" => array("year_fbn","plate_number"),
"orderby" => "meta_value ",
"order" => "ASC"
));
我知道这条线不会工作,"meta_key"=>array("year_fbn","plate_number"),
有人可以帮助我。谢谢
答案 0 :(得分:0)
您需要查询元字段,以便在JOIN
内WP_Query
进行编辑,然后使用posts_orderby
过滤器按照这些元字段对结果进行排序 - 别名使用格式为mt1.meta_value
。
// Function to replace the order by clause in the SQL generated by WP_Query
function custom_order_by( $order_by ){
return str_replace(
'menu_order',
'mt1.meta_value, mt2.meta_value, mt3.meta_value, mt4.meta_value',
$order_by
);
}
// args for WP_Query
$args = array(
"post_type" => "application-list",
"author" => $current_user->ID,
"meta_query" => array(
array(
"key" => "brand_fbn",
"compare" => "LIKE",
"value" => ""
),
array(
"key" => "model_fbn",
"compare" => "LIKE",
"value" => ""
),
array(
"key" => "year_fbn",
"compare" => "LIKE",
"value" => ""
),
array(
"key" => "plate_number",
"compare" => "LIKE",
"value" => ""
)
)
);
// add filter to modify order by clause
add_filter( 'posts_orderby', 'custom_order_by' );
// run the WP_Query
$ins = new WP_Query( $args );
// remove the filter so that other queries aren't affected.
remove_filter( 'posts_orderby', 'custom_order_by' );