Skip Navigation

[Resolved] Set Up Filter By Year

This support ticket is created 6 years, 5 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 -
- 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 -

Supporter timezone: Europe/London (GMT+00:00)

This topic contains 1 reply, has 2 voices.

Last updated by Nigel 6 years, 5 months ago.

Assisted by: Nigel.

Author
Posts
#1070460

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.

Thanks!

#1071277

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

Hi Michael

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.