I recently needed to sort query results to match the order of IDs passed to it for use in a WHERE … IN() clause. In MySQL, this can be done using the FIELD() function in the ORDERY BY clause. For Doctrine, which doesn’t have the FIELD() function and doesn’t allow functions in the ORDER BY clause, there’s a little more work needed to make use of it.
For the Stearns site, we need to list upcoming events on the home page. Using Flutter, I created a custom write panel for the events (and other items). The events are simply posts that have a custom date field attached to them.
I was attempting to use the “query_posts()” function to get the posts I need. I discovered that it is possible to use this function multiple times on a single page. I previously thought you were unable to because of “the loop”, but you only have to make a few accommodations for the page name and other such WordPress variables getting changed. I was able to use this to output the page data on our home page plus two categories of posts.
Unfortunately, “query_posts()” allows limiting by category and sorting by a custom key, but no less than, greater than, or other such comparisons with the meta key [wrong, see end of post]. So I decided to make my own SQL query, to be run with the “$wp_db->get_results()” function. The function allows a straight SQL query to be run. Then some other functions are used to put the result set into “the loop”. So, the code to run my custom query looks like the following: