Skip to content

Instantly share code, notes, and snippets.

@helgatheviking
Created February 4, 2020 02: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 helgatheviking/c12981e2355f6dd898c3e1ecc7d39deb to your computer and use it in GitHub Desktop.
Save helgatheviking/c12981e2355f6dd898c3e1ecc7d39deb to your computer and use it in GitHub Desktop.
Wordpress patch a missing JPG in image tag on save
/*
* Patch missing JPG from img
* @param int $post_ID Post ID.
* @param WP_Post $post_after Post object following the update.
*/
function kia_patch_missing_img_tags( $post_id, $post ) {
// If this is a revision, get real post ID
if ( $parent_id = wp_is_post_revision( $post_id ) ) {
$post_id = $parent_id;
}
$content = $post->post_content;
// Matching borrowed from https://wordpress.stackexchange.com/a/162405/6477
// we need a expression to match things
$regex = '/src="([^"]*)"/';
// we want all matches
preg_match_all( $regex, $content, $matches );
// reversing the matches array
$matches = array_reverse($matches);
$needs_update = false;
if( $matches ) {
foreach( $matches[0] as $match ) {
// Skip the matches that have a trailing jpg or png
if( strrpos( $match, '.jpg' ) !== false || strrpos( $match, '.png' ) !== false ) {
continue;
}
$needs_update = true;
// We presume we found an image tag with no trailing image type
$content = str_replace( $match, $match . '.jpg', $content );
}
if( $needs_update ) {
// unhook this function so it doesn't loop infinitely
remove_action( 'save_post', 'kia_patch_missing_img_tags', 10, 2 );
// update the post, which calls save_post again
wp_update_post( array( 'ID' => $post_id, 'post_content' => $content ) );
// re-hook this function
add_action( 'save_post', 'kia_patch_missing_img_tags', 10, 2 );
}
}
//wp_die(var_dump($matches));
}
add_action( 'save_post', 'kia_patch_missing_img_tags', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment