Skip Navigation

[Resolved] Views: Select posts created in last X days

This support ticket is created 5 years, 7 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
- 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Hong_Kong (GMT+08:00)

This topic contains 3 replies, has 2 voices.

Last updated by Luo Yang 5 years, 7 months ago.

Assisted by: Luo Yang.

Author
Posts
#1229681

i'm trying to create a view that filters by posts created in the last 7 days. what are the exact settings to achive this?

#1229768

Hello,

Yes, it is possible within Views filter hook "wpv_filter_query", for example, you can add below codes into your theme file functions.php:

add_filter('wpv_filter_query', function($query, $settings, $view_id){
	if( in_array($view_id, array(123)) ){
		$query['date_query']['after'] = date_i18n( get_option( 'date_format' ), strtotime( '-7 days' ) );
	}
	return $query;
}, 10, 3);

Please replace 123 with your post view's ID

More help:
https://toolset.com/documentation/programmer-reference/views-filters/#wpv_filter_query
When displaying a View listing posts, this filter is applied to the arguments being generated by the View settings before they are passed to the WP_Query class.

https://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters
after (string/array) - Date to retrieve posts after. Accepts strtotime()-compatible string,

#1229821

ok, thanks.
but with all the options you got in the views dialog, it's really not possible to do this without code? this is no problem to achieve using the date_query parameter (as in your example), but it can't be done directly in the views dialog? it seems that relative-to-today filters would be common. could this be a suggestion?

#1232007

Sorry for the late answer, yes, you are right, there isn't such a built-in feature within Views plugin, see our document:
https://toolset.com/documentation/user-guides/filtering-views-query-by-date/
There isn't such an option to filter the posts by "created in the last 7 days", you can add a feature request for it:
https://toolset.com/home/contact-us/suggest-a-new-feature-for-toolset/

Our developers will evaluate it.