Advertisement
vapvarun

Optimized attachment_url_to_postid using pre_attachment_url_to_postid for improved performance with

Feb 10th, 2025
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.56 KB | Software | 0 0
  1. /**
  2.  * Optimized attachment_url_to_postid using pre_attachment_url_to_postid for improved performance with Memcached.
  3.  *
  4.  * Why this helps:
  5.  * - **Reduced Database Load:** By caching attachment IDs, we significantly decrease the number of queries to the wp_postmeta table.
  6.  * - **Faster Response Times:** Cached results from Memcached are returned instantly, improving page load speeds.
  7.  * - **Efficient Cache Usage:** wp_cache_set ensures optimal cache hit rates in memory.
  8.  * - **Scalable Solution:** Ideal for large sites with high traffic, reducing MySQL CPU spikes caused by repetitive queries.
  9.  */
  10. add_filter('pre_attachment_url_to_postid', function ($pre, $url) {
  11.     if (empty($url)) {
  12.         return null;
  13.     }
  14.  
  15.     // Generate a unique cache key based on the URL
  16.     $cache_key = 'attachment_url_to_postid_' . md5($url);
  17.  
  18.     // Check object cache (Memcached)
  19.     $cached_post_id = wp_cache_get($cache_key, 'attachment_url_to_postid');
  20.  
  21.     if (false !== $cached_post_id) {
  22.         return (int) $cached_post_id; // Return cached ID if available
  23.     }
  24.  
  25.     global $wpdb;
  26.  
  27.     // Optimize the query to fetch the attachment ID
  28.     $post_id = $wpdb->get_var($wpdb->prepare(
  29.         "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attached_file' AND meta_value = %s LIMIT 1",
  30.         ltrim(parse_url($url, PHP_URL_PATH), '/')
  31.     ));
  32.  
  33.     // Cache in object cache (Memcached) for quick retrieval
  34.     wp_cache_set($cache_key, $post_id, 'attachment_url_to_postid', 12 * HOUR_IN_SECONDS);
  35.  
  36.     return $post_id ? (int) $post_id : null;
  37. }, 10, 2);
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement