Created
April 12, 2013 10:11
Run all images in the_content through WP Thumb
This file contains hidden or 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 | |
/** | |
* Run images inserted into posts through WP Thumb | |
* | |
* This serves a couple of purposes, 1 it allows us to delete the cache folder | |
* without having to worry about losing images and 2 it ensures all images | |
* are cropped to the correct size and limited to $content_width | |
* | |
* @var string | |
*/ | |
add_filter( 'the_content', function ( $content ) { | |
global $content_width; | |
if ( empty( $content ) || ! is_single() ) | |
return $content; | |
global $wpdb; | |
$content = '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' . $content; | |
$dom = new DomDocument; | |
@$dom->loadHTML( $content ); | |
$images = $dom->getElementsByTagName( 'img' ); | |
foreach ( $images as $image ) { | |
// Attempt to grab the post id from the class attribute | |
$post_id = preg_replace( '#[^0-9]#', '', $image->getAttribute( 'class' ) ); | |
if ( ! $post_id || ! get_post( $post_id ) ) | |
continue; | |
$width = $image->getAttribute( 'width' ); | |
$height = $image->getAttribute( 'height' ); | |
if ( $content_width && $width > $content_width ) | |
$width = $content_width; | |
$img = wp_get_attachment_image_src( $post_id, array( $width, $height ) ); | |
$image->setAttribute( 'width', $img[1] ); | |
$image->setAttribute( 'height', $img[2] ); | |
$image->setAttribute( 'src', $img[0] ); | |
} | |
$content = preg_replace( '/^<!DOCTYPE.+?>/', '', str_replace( array( '<html>', '</html>', '<head>', '</head>', '<body>', '</body>', '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' ), '', $dom->saveHTML() ) ); | |
return $content; | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment