Getting range filtering to work for custom field (type: date)
I was having trouble getting the range filtering to work for custom date fields.
For some reason the “Filter by:” option was not showing up when the Field Type was set to “Date”. When the field type is set to “Numeric”, you can see the “Filter by:” option.
After digging through the code, I found out why, the “filterable_type” property was not being set to “date” for the date field types, whereas for “numeric” field type the “filterable_type” property was set to “numeric”. The can be seen in /admin-columns-pro/classes/filtering/classes/model.php (Line 87: enable_filtering_custom_field).
To fix this, add the following code:
if ( in_array( $column->options->field_type, array( 'date' ) ) ) {
$column->set_properties( 'filterable_type', 'date' );
}
after
if ( in_array( $column->options->field_type, array( 'numeric' ) ) ) {
$column->set_properties( 'filterable_type', 'numeric' );
}
Now, you should be able to select a “Filter by:” option for custom date fields.
After adding a range filterable date field, none of my other filters were showing up. It turns out that in the “add_filtering_markup” function, every column was considered to have “filter_format” set to range. Which was strange because when i cross-checked with the configurations in the database, only the custom date field was filterable with filter_format set to “range”. After hours of debugging, it turns out ACP clones the first column-meta (if there are more than one custom field columns), when cloning, it copies the filter_format => range into the other columns.
To fix this, add the following code right before the array is returned:
/admin-columns-pro/codepress-admin-columns/classes/column/custom-field.php (Line 79: sanitize_options)
if (isset($options['filter']) && ! isset($options['filter_format'])) {
$options['filter_format'] = '';
}
Last but not least, the date range filters weren’t working properly. Turns out ACP was formatting the requested min & max dates to Ymd and comparing it numerically. The problem was, the date was saved as “Y-m-d H:i:s” format. In order to solve this I modified the following file:
/admin-columns-pro/classes/filtering/classes/model.php (Line 201: get_meta_query_range)
Replace the date query logic with:
if ( $min ) {
$min = DateTime::createFromFormat('Y-m-d', $min);
$meta_query[] = array(
'key' => $key,
'value' => $min->format('Y-m-d'),
'compare' => '>=',
'type' => 'DATE'
);
}
if ( $max ) {
$max = DateTime::createFromFormat('Y-m-d', $max);
$meta_query[] = array(
'key' => $key,
'value' => $max->format('Y-m-d'),
'compare' => '<=',
'type' => 'DATE'
);
}
I hope this helps someone, it’s a shame this didn’t work out of the box (now i have to make sure I update the code after ACP updates….).
For something I paid $200 for, i expect these issues to be non-existent.
You must be logged in to reply to this topic.