Performance improvement for resolve_image_id()
-
Hello! For WP installations with an object cache plugin installed, such as redis, caching the expensive resolve_image_id() function provides a nice speed boost. Here’s what we did–you’re welcome to use this code.
function resolve_image_id( $url ) { global $wpdb; $pattern = '/[_-]\d+x\d+(?=\.[a-z]{3,4}$)/'; $url = preg_replace( $pattern, '', $url ); $url = $this->get_pathinfo_from_image_src( $url ); $cacheKey = "gallery-custom-links-id-" . $url; $cacheGroup = "gallery-custom-links"; $cached = wp_cache_get($cacheKey, $cacheGroup); if ($cached !== false) { return $cached; } $query = $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE guid LIKE '%s'", '%' . $url . '%' ); $attachment = $wpdb->get_col( $query ); $result = empty( $attachment ) ? null : $attachment[0]; wp_cache_set($cacheKey, $result, $cacheGroup, 7*24*60*60); return $result; }
Viewing 6 replies - 1 through 6 (of 6 total)
Viewing 6 replies - 1 through 6 (of 6 total)
- The topic ‘Performance improvement for resolve_image_id()’ is closed to new replies.