WordPress.org

Codex

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

Return to Plugin API/Filter Reference