Order Posts by Custom Key revisited

I’ve gotten quite a few questions about how to get this to work on a specific page, or only within a specific category. I actually had the same issue when building the script originally. The trick is that you can’t just use the conditional tags in the functions page. At that point, it’s already too late because the queries have already been run. You have to create a function and then run it as a filter on one of the early WordPress initializing functions. I chose the wp() function. Here is my revised code (nearly straight from the client’s site).

add_action('wp', 'check_page');
function check_page () {
	if (is_page('The Page Name')) {
		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 = 'Price' ";

		  return $where;
		}
	}
}

In our case, we were sorting by the “Price” meta key and we were sorting from highest to lowest price. I hope this helps clear things up. Thanks to Paul Gray for sending us an email asking for some clarification.

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.