Skip to content

Instantly share code, notes, and snippets.

@mukeshpanchal27
Last active September 12, 2024 13:45
Show Gist options
  • Save mukeshpanchal27/c3a8b8fa5a18e988529401e7aab67263 to your computer and use it in GitHub Desktop.
Save mukeshpanchal27/c3a8b8fa5a18e988529401e7aab67263 to your computer and use it in GitHub Desktop.
MU plugin for priming the attachment cache for WordPress
<?php
/**
* Plugin Name: WPP Prime Attachment Cache
* Description: MU plugin for priming the attachment cache.
* Version: 1.0
*/
/**
* Primes attachment into the cache with a single database query.
*
* @since 6.7.0
*
* @param string $content The HTML content.
* @param string $context Optional. Additional context to pass to the filters.
* Defaults to `current_filter()` when not set.
* @return string The HTML content.
*/
function wp_prime_attachment_caches( $content, $context = null ) {
if ( null === $context ) {
$context = current_filter();
}
if ( ! preg_match_all( '/<img\s[^>]+>/', $content, $matches, PREG_SET_ORDER ) ) {
return $content;
}
// List of the unique `img` tags found in $content.
$images = array();
foreach ( $matches as $match ) {
list( $tag_name ) = $match;
if ( preg_match( '/wp-image-([0-9]+)/i', $tag_name, $class_id ) ) {
$attachment_id = absint( $class_id[1] );
if ( $attachment_id ) {
/*
* If exactly the same image tag is used more than once, overwrite it.
* All identical tags will be replaced later with 'str_replace()'.
*/
$images[ $tag_name ] = $attachment_id;
}
}
$images[ $tag_name ] = 0;
}
// Reduce the array to unique attachment IDs.
$attachment_ids = array_unique( array_filter( array_values( $images ) ) );
if ( count( $attachment_ids ) > 1 ) {
/*
* Warm the object cache with post and meta information for all found
* images to avoid making individual database calls.
*/
_prime_post_caches( $attachment_ids, false, true );
}
return $content;
}
add_filter( 'the_content', 'wp_prime_attachment_caches', 6 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment