Sort By Array Order


One of the great things about Wordpress’s Wp_Query() is the ability to sort results by the way ids are ordered in the post_in array. The same thing is achievable in raw SQL too. The thing to remember, is to pass either single numbers or individual strings to the FIELD function. If the ids are stored in a PHP array its easy enough to build up a query string using a loop or the implode function.

$ids = implode( array(2, 1, 3), "," );
$query = "SELECT id, title FROM table WHERE IN(2, 1, 3) ORDER BY FIELD(id, $ids) DESC";

You could also specify the keys and their values in an ordered list that would have the same affect.

$query = "SELECT id, title FROM table ORDER BY id = 2 DESC, id = 1 DESC, id = 3 DESC";

Other Resources