The media_library_months_with_files WordPress PHP filter allows you to override the list of months displayed in the media library.
Usage
add_filter('media_library_months_with_files', function($months) {
// your custom code here
return $months;
});
Parameters
- $months (stdClass[]|null) – An array of objects with month and year properties, or null for default behavior.
More information
See WordPress Developer Resources: media_library_months_with_files
Examples
Display only the last six months
Limit the list of months displayed in the media library to the last six months.
add_filter('media_library_months_with_files', function($months) {
$last_six_months = [];
$current_month = date('m');
$current_year = date('Y');
for ($i = 0; $i < 6; $i++) {
$month_obj = new stdClass();
$month_obj->month = $current_month;
$month_obj->year = $current_year;
array_push($last_six_months, $month_obj);
$current_month--;
if ($current_month == 0) {
$current_month = 12;
$current_year--;
}
}
return $last_six_months;
});
Display only months with specific years
Display months only for the years 2020 and 2022 in the media library.
add_filter('media_library_months_with_files', function($months) {
$allowed_years = [2020, 2022];
$filtered_months = array_filter($months, function($month_obj) use ($allowed_years) {
return in_array($month_obj->year, $allowed_years);
});
return $filtered_months;
});
Remove a specific month
Remove December 2021 from the list of months displayed in the media library.
add_filter('media_library_months_with_files', function($months) {
$filtered_months = array_filter($months, function($month_obj) {
return !($month_obj->month == 12 && $month_obj->year == 2021);
});
return $filtered_months;
});
Display only even months
Show only even months in the list of months displayed in the media library.
add_filter('media_library_months_with_files', function($months) {
$filtered_months = array_filter($months, function($month_obj) {
return $month_obj->month % 2 == 0;
});
return $filtered_months;
});
Sort months in ascending order
Display the list of months in the media library in ascending order.
add_filter('media_library_months_with_files', function($months) {
usort($months, function($a, $b) {
if ($a->year == $b->year) {
return $a->month - $b->month;
}
return $a->year - $b->year;
});
return $months;
});