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