Skip to content

Instantly share code, notes, and snippets.

@tormjens
Created April 24, 2015 12:41
Show Gist options
  • Save tormjens/0ad7a83b5b7e5f245646 to your computer and use it in GitHub Desktop.
Save tormjens/0ad7a83b5b7e5f245646 to your computer and use it in GitHub Desktop.
Download and replace images in a text
function id_replace_images($content) {
$dom = new domDocument;
$dom->loadHTML('<?xml encoding="UTF-8">' . $content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
// dirty fix
foreach ($dom->childNodes as $elem)
if ($elem->nodeType == XML_PI_NODE)
$dom->removeChild($elem); // remove hack
$dom->encoding = 'UTF-8'; // insert proper
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');
foreach ($images as $key => $image) {
$src = $image->getAttribute('src');
$img = trailingslashit( dirname(__FILE__) ) . '../' . $src;
$img_id = null;
if( !$img_id = id_get_image($img) ) {
$img_id = id_image($img);
}
if( $img_id ) {
$min_width = 1500;
$img = wp_get_attachment_image_src( $img_id, 'full' );
if( $img[1] > $min_width ) {
$src = anuna_img(home_url($img[0]), 'type=input&width=1500&height=99999&upscale=false&crop=false&echo=false&output=src&post_id=null');
$src = str_replace(home_url(), '', $src);
}
else {
$src = $img[0];
}
$image->setAttribute('src', $src);
}
else {
$image->parentNode->removeChild($image);
}
}
return $dom->saveHTML();
}
function id_get_image( $url ) {
$name = sanitize_file_name(basename($url));
global $wpdb;
$query = "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'attachment' AND guid LIKE '%/{$name}' LIMIT 1";
return $wpdb->get_var($query);
}
function id_image( $path ) {
if(!file_exists($path))
return;
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
$file_array = array(
'name' => basename( $path ),
'tmp_name' => $path
);
$id = media_handle_sideload( $file_array, 0 );
// Check for handle sideload errors.
if ( is_wp_error( $id ) ) {
return $id;
}
return $id;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment