This thread is resolved. Here is a description of the problem and solution.
Problem:
How to filter view result by a specific month of custom date field
Solution:
Well - you should use the view's shortcode attribute to filter view result by specific month with some adjustment in view's query using view's filter wpv_filter_query.
For exmaple:
[wpv-view name="view-filter-by-month" month="1"] // if January
I have CPT with a date field. How do I create a view that filters only the post with a specific month, say July. The year and day is not relevant. I have looked at https://toolset.com/documentation/user-guides/date-filters/ but couldn't figure it out.
Hello. Thank you for contacting the Toolset support.
Well - when you say you want to filter view with specific month, do you need a dropdown select filter that lists months as options or you just want to have static July month filter and display posts belongs to July month?
I would need guidance for both - filter by dropdown selection (month only) and more importantly for my current purpose, a static view to display a particular month's post.
Minesh isn't available, I will take care this thread.
For your question: I have CPT with a date field. How do I create a view that filters only the post with a specific month, say July. The year and day is not relevant
Is there a way to do a quick shortcode to return the month of the custom date field? The perhaps I could use the shortcode attribute in the views filter.
Luo is on vacation and I'm back to handle this ticket.
Well - to filter a view using month, for example:
[wpv-view name="view-filter-by-month" month="1"] // for january
[wpv-view name="view-filter-by-month" month="3"] // for march
As custom date field value stored as unix timestamp, you need to use view's filter wpv_filter_query .
For example - please add following code to your current theme's functions.php file:
add_filter('wpv_filter_query', 'remove_past_events', 10, 3);
function remove_past_events($query_args, $view_settings, $view_id) {
global $WP_Views;
global $wpdb;
if($view_id == 9999) {
$passed_month = $WP_Views->view_shortcode_attributes[0]['month']; // getting shortcode attribute value
$sql = "SELECT post_id FROM ".$wpdb->prefix."postmeta,".$wpdb->prefix."posts
WHERE (".$wpdb->prefix."postmeta.post_id = ".$wpdb->prefix."posts.ID)
AND ".$wpdb->prefix."postmeta.meta_key = 'wpcf-REPLACE-DATE-FIELD-SLUG'
AND month(FROM_UNIXTIME(".$wpdb->prefix."postmeta.meta_value)) = ".$passed_month."
AND ".$wpdb->prefix."posts.post_type = 'student'
AND ((".$wpdb->prefix."posts.post_status = 'publish' OR ".$wpdb->prefix."posts.post_status = 'private'))";
$res = $wpdb->get_col($sql);
if(!empty($res)){
$query_args['post__in'] = $res;
}
}
return $query_args;
}
Where:
- Replace 9999 with your original view ID,
- REPLACE-DATE-FIELD-SLUG with your original custom date field slug
- Replace student with your post type slug