Wordpress custom field - search-results sorted by value

只谈情不闲聊 提交于 2019-12-12 02:54:45

问题


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


来源:https://stackoverflow.com/questions/10016568/wordpress-custom-field-search-results-sorted-by-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!