I have a custom post type that has a date attribute.
I would like to create a filtering option to sort by year. The user needs to be able to select from a drop down a year between 1970 and the current year.
How do I set this up?
There is no obvious option when selecting New Filter > Date, despite this being a fairly obvious use case.
There are a few problems filtering by year as you describe.
The first is that if you add a filter for a date custom field to a View you'll have the datepicker UI for choosing the date, when all you need is a select dropdown with the years.
But then the query itself would need customising using the Views API (specifically the wpv_filter_query filter: hidden link).
Date fields are stored as UNIX timestamps (and so are a point in time to the nearest second), so your filter would actually need modifying to be a BETWEEN comparison (from 1 Jan 00:00:00 to 31 Dec 23:59:59) with some custom code.
An alternative would be if you had a taxonomy for the year (with terms 1970, 1971, 1972... etc.) assigned to the posts.
The it would be trivial to add a filter for the year to your View which included the years in a dropdown and required no customisation of the query. (And would also mean more performant filtering.)
But! You presumably would rather avoid the duplication of entering a date in the date field and then also having to set the year for the taxonomy.
I think it would be simpler to add a code snippet that used the save_post hook to automatically set the taxonomy based upon the date field whenever a post was saved.
What do you think? I can help with that if you need it.