I am building a WP site with an events feature. The events page was made with custom post types.
I want to make it possible for people to search/ filter events by dates. For example, they can search for all events happening between 2nd December, 2011 and 1st March, 2012 and get results from events that have their dates between the months of December and March (ie. december, january, february and march).
I want to know the best way to go about this. Any ideas?
You can see an example of what I want to achieve by looking at the “Search events by date” feature on this page http://www.londontown.com/events
If that won’t be possible, is there any way I can get them to search for events happening between certain months, say December and February(excluding the days)?
Thanks in advance.
There two things that you need to do to make this happen:
1) Create metadata for the data for each event
2) Query for the posts using meta_query
For #1, you need to add a metabox that allows the user to add a date for the event. This data should be stored as metadata using the
add_post_meta
orupdate_post_meta
. I would encourage you to read about adding metadata if you are not familiar with how to do it:http://codex.wordpress.org/Function_Reference/add_meta_box
http://www.wproots.com/complex-meta-boxes-in-wordpress/
For #2, assuming that your have saved the date values in an orderable manner (e.g., YYYY-MM-DD), you can use the meta_query parameter of within a new instance of WP_Query to get the appropriate date range. This method assumes that your meta_key is “_my-datetime-from”. For instance, you can get the posts in October and November 2011 with the following:
How do you store the event date: using the default
post_date
field of the post or a custom meta field?If you’re using the default
post_date
, you can use the filterposts_where
to add conditions for search, like this:For more examples, please check out the Codex.
In case of using custom field, I guess you have to write your own custom MySQL queries. It’s a little bit more complicated. Here’s an example: