Make WordPress Core

Opened 6 weeks ago

Last modified 6 weeks ago

#61383 new enhancement

Add new filter to attachment_url_to_postid() for short circuit

Reported by: apermo's profile apermo Owned by:
Milestone: 6.7 Priority: normal
Severity: normal Version:
Component: Media Keywords: has-patch
Focuses: Cc:

Description

The function attachment_url_to_postid() will receive a relative url and then use the query following query to get the corresponding post_id for the attachment.

SELECT post_id, meta_value FROM wp_postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = '2024/06/my-image.jpg'

On large installations, this will be slow, resulting in long delays upon saving. In my example we are talking about 4s per query, since the installation has 500k images in the database. And if a post has a gallery, this can result in save times above 30s. So even for less extreme sizes this query will result in long wait times for editors, if they save posts with lots of images.

Adding a new column to wp_post or a new table to core is unlikely, since the default behavior works fine for standard installations.

So in my case I want to add a custom table, to speed up my installation. And while it currently already is possible to filter the query before it is executed using the filter query this requires a to check all incoming queries, if it possibly is one those that I want to replace.

This is why I propose to add a filter at the beginning of the function, which allows to short circuit the function if anyone wants to use a custom method.

As already mentioned, I've checked the following alternatives for my particular site and I think adding the filter will add value here.

  • Using query deeper inside the function. Will work, but is not ideal since you need to check all queries, and on top, it will only allow you to use the database as source, so if you'd have a different method of getting the result, it would require you to fake a result, or use the filter at the end of the function, after you already did the query.
  • Adding an index to the meta_value column. This speeded up the query from 4s to 20ms in my case, but I do not dare to do so on a production system, since I have no idea what side effects this will have.
  • Overriding the function will not work, since the function does not come wrapped in a if ( function_exists() ) and the function is used twice in core, as well as in Yoast SEO and ACF.

Which comes to the conclusion, by adding the attached filter, it will make it easier to allow custom methods of retrieving the post_id faster for special setups.

Attachments (1)

attachment_url_to_postid.patch (916 bytes) - added by apermo 6 weeks ago.
Patch for the ticket.

Download all attachments as: .zip

Change History (2)

@apermo
6 weeks ago

Patch for the ticket.

#1 @audrasjb
6 weeks ago

  • Milestone changed from Awaiting Review to 6.7
Note: See TracTickets for help on using tickets.