I had to implement the following:
- Change the admin UI to include my custom filters
add_action('wp_enqueue_media', function () {
wp_enqueue_script('media-library-taxonomy-filter', get_stylesheet_directory_uri() . '/assets/js/custom-media-filter.js', array('media-editor', 'media-views'));
});
- In the custom-media-filter.js I am appending the custom select HTML and every time my custom select is changed, add the query parameters in the URL and redirect with this parameter and value
jQuery(document).ready(function () {
jQuery('.filter-items').append('<select class="form-select" aria-label="Custom filter document_category" id="page-document_category"><option>-Choose-</option><option value="document">Document</option><option value="template">Template</option></select>');
jQuery('#page-document_category').change(function (e) {
insertParam('document_category', this.value)
});
// insert and redirect with new value
function insertParam(key, value) {
key = encodeURIComponent(key);
value = encodeURIComponent(value);
// remove all other parameters
var kvp = [];
kvp.push(key + '=' + value);
document.location.search = params;
}
});
- Add action in my functions.php binding to the
pre_get_posts
add_action('pre_get_posts', 'my_custom_filter');
and create my custom function my_custom_filter
that changes the meta query only when my custom filters are sent to the URL
if (!function_exists('my_custom_filter')) {
function my_custom_filter($wp_query_obj)
{
$url_query = explode('&', $_SERVER['QUERY_STRING']);
$params = array();
foreach ($url_query as $param) {
if (isset($param) && $param[0] !== '') {
// prevent notice on explode() if $param has no '='
if (strpos($param, '=') === false) $param += '=';
list($name, $value) = explode('=', $param, 2);
$params[urldecode($name)][] = urldecode($value);
urldecode_deep($params);
}
}
$found = false;
if (isset($params['document_category'])) {
$meta_key = 'document_category';
$meta_value = $params['document_category'][0];
$found = true;
}
// here i can add more filters
// else if ($params['document_type']) {
// $meta_key = 'document_type';
// $meta_value = $params['document_type'][0];
// $found = true;
// }
if ($found) {
$meta_query = array(
array(
'key' => $meta_key,
'value' => $meta_value,
'compare' => '=',
),
);
$wp_query_obj->set('meta_query', $meta_query);
$wp_query_obj->set('orderby', 'meta_value_num');
$wp_query_obj->set('order', 'ASC');
}
return;
}
}