vapvarun icon

Optimized attachment_url_to_postid using pre_attachment_url_to_postid for improved performance with

vapvarun | PRO | 02/10/25 04:45:48 PM UTC | 0 ⭐ | 7043 👁️ | Never ⏰ | []
PHP |

1.56 KB

|

Software

|

0 👍

/

0 👎

/**
 * Optimized attachment_url_to_postid using pre_attachment_url_to_postid for improved performance with Memcached.
 * 
 * Why this helps:
 * - **Reduced Database Load:** By caching attachment IDs, we significantly decrease the number of queries to the wp_postmeta table.
 * - **Faster Response Times:** Cached results from Memcached are returned instantly, improving page load speeds.
 * - **Efficient Cache Usage:** wp_cache_set ensures optimal cache hit rates in memory.
 * - **Scalable Solution:** Ideal for large sites with high traffic, reducing MySQL CPU spikes caused by repetitive queries.
 */
add_filter('pre_attachment_url_to_postid', function ($pre, $url) {
    if (empty($url)) {
        return null;
    }
 
    // Generate a unique cache key based on the URL
    $cache_key = 'attachment_url_to_postid_' . md5($url);
 
    // Check object cache (Memcached)
    $cached_post_id = wp_cache_get($cache_key, 'attachment_url_to_postid');
 
    if (false !== $cached_post_id) {
        return (int) $cached_post_id; // Return cached ID if available
    }
 
    global $wpdb;
 
    // Optimize the query to fetch the attachment ID
    $post_id = $wpdb->get_var($wpdb->prepare(
        "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attached_file' AND meta_value = %s LIMIT 1",
        ltrim(parse_url($url, PHP_URL_PATH), '/')
    ));
 
    // Cache in object cache (Memcached) for quick retrieval
    wp_cache_set($cache_key, $post_id, 'attachment_url_to_postid', 12 * HOUR_IN_SECONDS);
 
    return $post_id ? (int) $post_id : null;
}, 10, 2);
 

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎