Wordpress custom field - search-results sorted by

2019-03-03 17:28发布

问题:

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.

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;
}

回答1:

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' );