Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Run all images in the_content through WP Thumb
<?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
You can’t perform that action at this time.