WordPress.org

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Plugin API/Filter Reference/posts orderby

This page is marked as incomplete. You can help Codex by expanding it.

Description

This filter is applied before a post-retrieving SQL statement is executed. Use it to make custom modifications to the orderby. WP_Query is versatile but there may be situations where you need to orderby a value that is in a separate database, a custom equation, etc.


Examples

Consider the following code. In tandem with a rating plugin that uses a separate database table, sorting by rating value can be achieved with posts_orderby in tandem with the post_join_paged filter.

add_filter('posts_orderby', 'edit_posts_orderby');
add_filter('posts_join_paged','edit_posts_join_paged');

function edit_posts_join_paged($join_paged_statement) {
	$join_paged_statement = "LEFT JOIN wp_gdsr_data_article gdsra ON gdsra.post_id = wp_posts.ID";
	return $join_paged_statement;	
}

function edit_posts_orderby($orderby_statement) {
	$orderby_statement = "(gdsra.user_votes_total_sum/gdsra.user_votes_count) DESC";
	return $orderby_statement;
}

Second Parameter Example

This filter is extremely powerful - it will apply a new or updated ORDERBY to every SQL SELECT statement generated by the WP_Query class. So it's also very easy to break WordPress functionality using this filter.

Fortunately, the posts_orderby filter will also pass a reference to the current WP_Query instance as a second parameter. It's good practice to always check the referenced WP_Query to ensure only the desired SQL query is being modified. This is especially true on a modern site, where in many cases more than one WP_Query is run per request.

// Add the callback to the posts_orderby filter
add_filter('posts_orderby', 'orderby_pages_callback', 10, 2);

// The posts_orderby filter
function orderby_pages_callback($orderby_statement, $wp_query) {
	# Verify correct post type, or any other query variable
	if ($wp_query->get("post_type") === "page") {
		# In this trivial example add a reverse menu order sort
		return "wp_posts.menu_order DESC";
	} else {
		# Use provided statement instead 
		return $orderby_statement;
	}
}

// Example WP_Query that loads all pages.
// The above filter callback will cause these to have a reverse menu order sort
$pages_query = new WP_Query(array(
	"post_type" => "page"
));

You can also prevent any posts_orderby callbacks from being loaded by using the suppress_filters in your own WP_Query calls:

$pages_query = new WP_Query(array(
	"post_type" => "page",
	"suppress_filters" => true,  // No posts_orderby filters will be run
));

Return to Plugin API/Filter Reference

http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters