WordPress自定义字段-搜索结果按值排序
问题描述:
我有一个自定义字段,称为 rating,值从1到10。
我想要的是可以选择(例如单击按钮或类似的按钮)
I have a custom field called "rating" with value from 1 to 10. What I want is that you can choose (like click on a button or something like that) to sort the search-results depending on the rating.
我找到了这段代码。但是问题是您无法选择是否通过评分来排序帖子。它会自动订购帖子。
这是我复制并粘贴到functions.php中的代码。
I've found this code. But the problem is that you can't choose wether to order the post by rating or not. It automatically orders the posts. This is the code which I've copy and paste into the functions.php
add_filter('posts_join', 'add_join' );
function add_join($pjoin){
global $wpdb;
$pjoin .= "LEFT JOIN (
SELECT *
FROM $wpdb->postmeta
WHERE meta_key = 'rating' ) AS postmeta ON $wpdb->posts.ID = postmeta.post_id";
return ($pjoin);
}
add_filter('posts_orderby', 'change_sortorder' );
function change_sortorder( $orderby ){
global $wpdb;
$orderby = "postmeta.meta_value+0 DESC";
return $orderby;
}
答
如果使用此代码,只需将?rating = desc添加到您的网址中,您就会看到评级以降序排列。
If you use this code you can just add ?rating=desc to your url and you'll see the ratings in descending order.
function register_my_qv() {
global $wp;
$wp->add_query_var( 'rating' );
}
add_action( 'init', 'register_my_qv' );
function map_my_qv( $wp_query ) {
if ( $meta_value = $wp_query->get( 'rating' ) ) {
$wp_query->set( 'meta_key', 'rating' );
if($meta_value == 'asc') {
$wp_query->set( 'orderby', 'meta_value_num' );
$wp_query->set( 'order', 'asc' );
} elseif ($meta_value == 'desc') {
$wp_query->set( 'orderby', 'meta_value_num' );
$wp_query->set( 'order', 'desc' );
} else {
$wp_query->set( 'meta_value', $meta_value );
}
}
}
add_action( 'parse_query', 'map_my_qv' );