The WP_Query class in WordPress is extremely robust and allows you to construct just about any kind of query you need for retrieving data from the wp_posts table, but there are still scenarios you will encounter when building your plugins that WP_Query doesn’t support. Before WordPress 3.7, the posts_where filter was used primarily for setting up date-range queries and queries that pulled all posts except those by a set of authors. Both of these kind of queries are supported in WordPress 3.7+, but there are still numerous cases where the posts_where filter is the tool of choice for querying just the data you need.
The video below walks (quickly) through how I used the posts_where filter to set up queries for specific date ranges in Easy Digital Downloads. We needed to query payment data (stored in wp_posts) between two dates, which at the time was not supported by the default WP_Query args.
The EDD_Stats class is the base class we use to setup the date properties. Once the dates are setup, we use the posts_where filter to modify the where clause of the SQL query that WordPress performs. You can see our payments_where() callback here and how the callback is used here.
If you are not familiar with how the SQL where clause works, I’d suggest you read up on it. Here are a few good articles:
- http://www.w3schools.com/sql/sql_where.asp
- http://code.tutsplus.com/tutorials/writing-custom-queries-in-wordpress–wp-25510
- http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where
- http://wordpress.stackexchange.com/questions/5546/how-to-correctly-call-custom-field-dates-into-a-posts-where-filter-using-sql-sta
That’s not nearly as difficult as I thought it would be. I have no use for it at the moment but I’ll be back to reference it I’m sure. A few little ideas are flowing already.
hi!
i’m peculiarly happy to read your paper.
I try to understand if the post_where filter can be user for front-end developpment…!
i’m looking for a way to use a searchform on my homepage that gives a resultspage out from my database, and given posts linked beetween two dates.
ex: the user select a category (‘film’) a tag (‘action’) a start date ( when the film is played in one cinema) and the end date, when it does not anymore.
when he clicks ‘okay’ the results page gives all the results that match.
thank you really!