I’m creating a site in wordpress which holds information on television programs. I’m using custom fields to select each post.
The table looks something like this
+----+---------+----------+------------+
| id | post_id | meta_key | meta_value |
+----+---------+----------+------------+
| 1 | 1 | name | Smallville |
| 2 | 1 | season | 1 |
| 3 | 1 | episode | 1 |
| 4 | 2 | name | Smallville |
| 5 | 2 | season | 1 |
| 6 | 2 | episode | 2 |
+----+---------+----------+------------+
Basically what I need to do is select all of the tv shows with the name “Smallville” and sort them by season then by episodes. I thought it would be fairly simple but everything I have tried returns nothing.
Could you please explain how I can do this?
You can do something like this:
This will give you the result:
In this form it is much easier for any operations.
What you need is to add:
Combine the rows using a self-join, and you’re good to go:
A more general case: sort-of conversion from your format to a more normal relational DB format:
For the actual sorting you can’t reuse the season / episode values (those aren’t assigned yet while sorting), so you have to copy/paste the subquery into the ORDER BY clause:
No need to do direct SQL.
You’ve got access to the SQL query through the WP_Query object. Check out the filters surrounding the where clause in the WP_Query object (there is more than 1 way to get at it) and simply modify the default WP_Query parts before they’re concatenated together.
Start by setting up a WP_Query object that gets all the posts by postmeta key & postmeta value, and then tack on a bit more to the where clause to do some extra conditionals.
There’s another filter that allows you to get at the ordering section of the SQL query so you can modify that.
There’s no reason to hand write SQL here, just modify what has already been built for you.
the idea is to join the table to itself 3 times where for each of them take rows for a given meta_key: