This question is almost what Im trying to achieve. Create a filter for posts based on a custom field.
My custom field is a date and I would like to create a date filter (monthly) based on this custom field for the post listing admin screen.
I’m not using the normal date as this is an historical website I’m creating and some posts are from many years ago.
Add a query variable to store the month
So first of all it’ll be necessary to create a custom query variable – this will store the month we’re after (in 2012/6) format. I’ll call it
custom_month
, but its best practise to prefix it to avoid clashes with other plug-ins:Add the drop-down
The query variable will now be recognised and any given value stored by WordPress in the main query (global
$wp_query
).Next we create the drop-down to go at the top of the post admin table (this can be changed to be any post type).
The above gets an array of months a month object consists of:
Obviously
wpse57344_get_months()
doesn’t exist natively – we’ll construct it later.Assuming with an array of months, we create the drop-down with each option having the value of the form
yyyy/mm
. I’ve given the form the same name as the query variable we added.Altering the query
When a month in the drop-down is selected, the month in
yyyy/mm
is posted as the value forcustom_month
. Because we’ve registered this variable name with WordPress we can access it through$query->get('custom_month')
.So we check if its empty or not – if its not, then we restrict to posts where their meta value data is in that month. To do that we use a meta query and the
BETWEEN
operator.Get the months
It remains then to define th function
wpse57344_get_months()
. We need to query the postmeta table and pick out distinct months from the dates in your posts’ meta. In the following I assume that your date is stored with key ‘customdate’ and has format (as indicated in comments)yyyy/mm/dd
.This returns an array of month objects in the desired format.