Created
March 19, 2019 10:38
-
-
Save Langmans/5f8357823e4bb1674a1af1667c61b6f3 to your computer and use it in GitHub Desktop.
fix wordpress missing image urls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_filter( 'template_redirect', function () { | |
global $wp_query; | |
if ( $wp_query instanceof WP_Query && | |
isset( $wp_query->query['pagename'] ) && | |
$wp_query->is_404() | |
) { | |
$uploads_dir = wp_get_upload_dir(); | |
$uploads_dir_pattern = '^/?' . preg_quote( trim( $uploads_dir ['relative'], '/' ) . '/', '@' ); | |
if ( preg_match( '@' . $uploads_dir_pattern . '(?<subdir>.*/)(?<name>(?<filename>[^/]+)-(?<width>\d+)x(?<height>\d+)\.(?<extension>jpe?g|gif|png))@i', $wp_query->query['pagename'], $m ) ) { | |
$q = new WP_Query( [ | |
'post_type' => 'attachment', | |
'posts_per_page' => 1, | |
'name' => $m['filename'], | |
] ); | |
if ( $q->found_posts === 1 ) { | |
/** @var WP_Post $attachment */ | |
$attachment = $q->posts[0]; | |
$editor = wp_get_image_editor( get_attached_file( $attachment->ID ) ); | |
if ( ! $editor instanceof WP_Error ) { | |
$editor->resize( $m['width'], $m['height'], true ); | |
$save_to = $uploads_dir['basedir'] . '/' . $m['subdir'] . $m['name']; | |
$save_url = $uploads_dir['baseurl'] . '/' . $m['subdir'] . $m['name']; | |
$save_ret = $editor->save( $save_to ); | |
if ( ! $save_ret instanceof WP_Error ) { | |
wp_safe_redirect( $save_url ); | |
} | |
} | |
} | |
} | |
} | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment