[wp-trac] [WordPress Trac] #63279: Improve `media_library_months_with_files` inside `wp_enqueue_media()`
WordPress Trac
noreply at wordpress.org
Mon Apr 14 16:18:40 UTC 2025
#63279: Improve `media_library_months_with_files` inside `wp_enqueue_media()`
-------------------------+-----------------------------
Reporter: apermo | Owner: (none)
Type: enhancement | Status: new
Priority: normal | Milestone: Awaiting Review
Component: Media | Version: 4.7.4
Severity: normal | Keywords:
Focuses: |
-------------------------+-----------------------------
As described in the filter, the query can and will be expensive for large
media libraries.
The downside of the given implementation is, that it requires a fully
custom implementation. If you want to just store the result of the query
in a transient there is currently no way to achieve this.
Ideal would be a `get_media_library_months_with_files()` that would have
been added to `media_library_months_with_files` at it's introduction.
{{{#!php
<?php
function wp_enqueue_media( $args = array() ) {
//...
/**
* Allows overriding the list of months displayed in the media
library.
*
* By default (if this filter does not return an array), a query
will be
* run to determine the months that have media items. This query
can be
* expensive for large media libraries, so it may be desirable for
sites to
* override this behavior.
*
* @since 4.7.4
*
* @link https://core.trac.wordpress.org/ticket/31071
*
* @param stdClass[]|null $months An array of objects with `month`
and `year`
* properties, or `null` for
default behavior.
*/
$months = apply_filters( 'media_library_months_with_files', null
);
if ( ! is_array( $months ) ) {
$months = $wpdb->get_results(
$wpdb->prepare(
"SELECT DISTINCT YEAR( post_date ) AS
year, MONTH( post_date ) AS month
FROM $wpdb->posts
WHERE post_type = %s
ORDER BY post_date DESC",
'attachment'
)
);
}
//...
}
}}}
Since that can't be done now without the uncertainty if it could break
things depending on the priority used by third parties.
I see 2 reasonable approaches to improve this.
1. Add a `do_action( 'post_media_library_months_with_files', $months );`
just after the query. This could be used to fill a transient that could be
read in the filter `media_library_months_with_files`, the downside would
be that splitting the get and set of the transient, would be
counterintuitive.
2. Move the query to a distinct `funtion
get_media_library_months_with_files()` which could be used inside
`media_library_months_with_files` to fill a transient. This approach seems
the more favorable to me, and I will prepare this as a PR.
While it is unlikely that the query will ever change, I still think it
should not be required to copy core code, just to create a transient.
--
Ticket URL: <https://core.trac.wordpress.org/ticket/63279>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list