Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save eSaner/36c78ee60d24b4753c7cd03386ef68d8 to your computer and use it in GitHub Desktop.
Save eSaner/36c78ee60d24b4753c7cd03386ef68d8 to your computer and use it in GitHub Desktop.
<?php
/**
* WP Search & Replace Image Block Thumbnail URLs
*
* Helpful after regenerating image thumbnails. Designed to run in a custom page template.
* Note: limit get_posts() results if PHP times out.
*
* @author Eric Saner
*/
// Define image sizes
$image_sizes = ['small', 'medium', 'large'];
// Create empty array to store posts that will be updated
$updated_posts = [];
// Get all posts
$posts = get_posts([
'post_type' => 'post',
'numberposts' => -1
]);
// Loop through post content
foreach ($posts as $post) {
// Continue if no content
if (!$post->post_content) {
continue;
}
// Get all image blocks from block comment to adjacent figure tag
preg_match_all('/\s*<!-- wp:image[\s\S]+?<\/figure>/', $post->post_content, $images, PREG_SET_ORDER);
// Continue if no image blocks
if (!$images) {
continue;
}
// Create empty search and replace arrays to store image URLs
$search = [];
$replace = [];
// Loop through image blocks
foreach ($images as $image) {
// Isolate block comment
preg_match('/\s*{[\s\S]+?}/', $image[0], $comment);
// Continue if no comment
if (!$comment) {
continue;
}
// Convert block comment to json
$image_data = json_decode($comment[0]);
// Continue if no json data
if (is_null($image_data) || !is_object($image_data)) {
continue;
}
// Continue if no image ID, no sizeSlug, or image size is not a valid insertable size
$no_image_id = !isset($image_data->id);
$no_image_size = !isset($image_data->sizeSlug) || !in_array($image_data->sizeSlug, $image_sizes);
if ($no_image_id || $no_image_size) {
continue;
}
// Isolate image src attribute
preg_match('/src="([^"]*)"/i', $image[0], $old_src);
// Fill search and replace arrays with old and new image urls
$search[] = substr($old_src[0], 5, -1);
$replace[] = wp_get_attachment_image_url($image_data->id, $image_data->sizeSlug);
}
if ($search && $replace) {
// Update post content with new image urls
wp_update_post([
'ID' => $post->ID,
'post_content' => str_replace($search, $replace, $post->post_content)
]);
// Add post to $updated_posts
$updated_posts[] = $post;
}
}
?>
<h2>Total Posts Updated: <?= count($updated_posts) ?></h2>
<?php
// Output list of updated posts
if ($updated_posts) {
?>
<ul>
<?php
foreach($updated_posts as $p) {
?>
<li><?= $p->post_title ?> | <a href="<?= get_the_permalink($p->ID) ?>"><?= $p->ID ?></a></li>
<?php
}
?>
</ul>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment