Skip to content

Instantly share code, notes, and snippets.

@Lovor01
Created October 21, 2023 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lovor01/78d79eece512c26d61711a55b732f8e6 to your computer and use it in GitHub Desktop.
Save Lovor01/78d79eece512c26d61711a55b732f8e6 to your computer and use it in GitHub Desktop.
Replace srcset
<?php
/**
* add sizeSlug attribute where it is missing and update image src accordingly
*/
// alternative only for fixing sizeSlug:
// wp search-replace '(<!-- wp:image\s{(?!.*"sizeSlug")[^}]*)' '$1,\"sizeSlug\":\"full\"' gr8_posts --regex --regex-delimiter='/' --include-columns=post_content --log=C:\Users\Admin\Downloads\replace.log --precise
$posts = get_posts( ['post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => -1] );
echo 'Found ' . count($posts) . "posts\n\n";
foreach ( $posts as $post ) {
// sizeSLug match: '/<!-- wp:image\s{(?!.*"sizeSlug")[^}]*/'
// $matches[1] - id, $matches[2] - sizeSlug
echo "Replacing in $post->post_title\n";
$replaced = preg_replace_callback('/<!-- wp:image.*?"id":(\d+)[^"]*(?:"sizeSlug":"(.*?)")?.*?<!-- \/wp:image -->/s', function($matches) use ($post) {
$sizeSlug_exists = isset($matches[2]);
$image_size = $sizeSlug_exists ? $matches[2] : 'full';
$new_image_url = wp_get_attachment_image_url( $matches[1], $image_size );
$replacement = $sizeSlug_exists
? $matches[0]
: preg_replace('/([^}]+)/s', '$0,"sizeSlug":"full"', $matches[0], 1);
$replacement = preg_replace('/(<img.*src=").*"/sU', "$1$new_image_url\"", $replacement);
echo $replacement . "\n\n";
return $replacement;
}, $post -> post_content);
$result = wp_update_post( ['ID' => $post->ID, 'post_content' => $replaced], true, false );
if (is_wp_error($result)) {
$errors = $result->get_error_messages();
foreach ($errors as $error) {
echo $error;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment