Skip to content

Instantly share code, notes, and snippets.

@tcrsavage
Created August 5, 2013 08:37
Show Gist options
  • Save tcrsavage/6154325 to your computer and use it in GitHub Desktop.
Save tcrsavage/6154325 to your computer and use it in GitHub Desktop.
Replace broken images in post content with a default image - Useful for dev environments
add_filter( 'the_content', function( $content ) {
$content_path = ( defined( 'IMAGE_REPLACER_WP_CONTENT_PATH' ) ) ? IMAGE_REPLACER_WP_CONTENT_PATH : WP_CONTENT_DIR;
$content_url = ( defined( 'IMAGE_REPLACER_WP_CONTENT_URL' ) ) ? IMAGE_REPLACER_WP_CONTENT_URL : WP_CONTENT_URL;
preg_match_all( '/<img(?:\s|.)+?src="((?:\s|.)+?)"(?:\s|.)+?\/?>/', $content, $matches );
if ( empty( $matches[1] ) )
return $content;
foreach ( $matches[1] as $match ) {
$file_path = str_replace( $content_url, $content_path, $match );
if ( file_exists( $file_path ) )
continue;
$content = str_replace( $match, ( defined ( 'IMAGE_REPLACER_DEFAULT_IMAGE_URL' ) ) ? IMAGE_REPLACER_DEFAULT_IMAGE_URL : $content_url . '/default.jpg', $content );
}
return $content;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment