Order Posts by a Custom Key

Just recently, we completed a website using WordPress for a realtor named Jon Dishon. One of his requests was to have his listing be ordered by price. Since we created his listings from simple posts with WordPresss’ Custom Keys, it was difficult for us to do this since Price is one of those keys. We wrote some special code to join the custom keys to the query being run for a specific page. We put the code in the functions.php page of the custom theme we created. Below is the code to sort by a custom key:

add_filter('get_previous_post_sort', 'sort_it');
add_filter('get_next_post_sort', 'sort_it');
add_filter('posts_orderby', 'sort_it' );
add_filter('posts_join', 'join_it' );
add_filter('posts_where', 'where_it' );

function sort_it () {
	global $wpdb;
	return " $wpdb->postmeta.meta_value DESC ";

function join_it( $join ) {
	global $wpdb;
	$join .= " LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id) ";
	return $join;

function where_it( $where ) {
	global $wpdb;
	$where .= "AND $wpdb->postmeta.meta_key = '' ";
	return $where;

NOTE: This code will run on every page whether you want it to or not. Be sure to use it only on the pages you want by wrapping this code in any of the conditional tags listed on the Codex.

How Can We Help You?

We want to build your next project.

Connect with Pixel Jar

Our Community

Subscribe to learn more about the goings on at Pixel Jar and AdSanity.
  • This field is for validation purposes and should be left unchanged.