I'm trying to set up a query filter to filter posts by date on an archive template: That is, show posts that have been posted within the last week, month, year, etc.
I know this can be done with the date query filters in a custom view, but I'd like the user to be able to select the date range in archive view from a dropdown menu. That way I don't have to set up a view/page for every time period, and the user can switch between time periods more easily. It would be a more elegant solution.
I understand that one of the problems is that WordPress doesn't save the post date in date format, but as a timestamp. Yet, on this support page (https://toolset.com/documentation/user-guides/date-filters/ ) it suggests that this can be done by setting up a "date" custom field and then applying a query filter to that custom field. However, I don't understand how the custom field could automatically be populated with the post date.
Or is there another, better way I can do this? It seems to me that being able to quickly filter by "posts published in the last x-days/months/years" or "between x and y" would be something a lot of people might find useful.
Dear Oliver,
There isn't such a built-in feature within Views plugin, Views does support the filter on post date:
https://toolset.com/documentation/user-guides/filtering-views-query-by-date/
But Views does not support the dropdown menu you mentioned above:
show posts that have been posted within the last week, month, year, etc.
So it needs custom codes, for example you can manually setup the dropdown menu, and apply the post date filter with wordpress built-in action hook pre_get_posts:
https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts
For your reference.
It seems that if the post date value were able to be copied to a custom field (in date format, not timestamp), then I could use the built in query filter (by date) to narrow the time frame of the posts. And then I wouldn't have to do any custom coding. Is there a way to add something to functions.php to pass the date the post was published to a custom field in toolset?
It depends on yourself, both ways should be able to work, but I recommend you try the workaround I mentioned above:
https://toolset.com/forums/topic/incorporating-dropdown-date-filter-in-an-archive-template/#post-564533
if you need to copy the post date into a custom date field, it needs some custom codes, for example you can try with the WordPress built-in action hook save_post, like this:
1) When user edit a post, use action hook save_post to trigger an custom PHP function:
https://developer.wordpress.org/reference/hooks/save_post/
You will be able to get the post ID
2) in this PHP function, get the post date of specific post
https://codex.wordpress.org/Function_Reference/get_the_date
3) Save above post date value into custom date field:
https://codex.wordpress.org/Function_Reference/update_post_meta
For your reference