Skip to content

Instantly share code, notes, and snippets.

@k1sul1
Last active February 18, 2016 12:26
Show Gist options
  • Save k1sul1/62ffad6d679b094396fc to your computer and use it in GitHub Desktop.
Save k1sul1/62ffad6d679b094396fc to your computer and use it in GitHub Desktop.
Optimismia.
<?php
$dryRun = true;
$posts = get_posts(array("post_type" => (!empty($_GET['type']) ? $_GET['type'] : 'post'), "posts_per_page" => -1)); // post_type is kinda reserved.
foreach($posts as $post){
$id = $post->ID;
if(has_post_thumbnail($id)){
continue;
// it's already converted.
}
$image = '';
$imageRegex = '/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i';
$nmatches = preg_match_all($imageRegex, $post->post_content, $matches);
if ($nmatches) {
$image = $matches[1][0];
// Additional check for spaces in filename
$image = str_replace(' ', '%20', $image);
}
$dictionary = [
"/modules/file/icons/application-pdf.png",
"/modules/file/icons/x-office-document.png"
];
if(in_array($image, $dictionary)){
// Blacklist, if filename is this, don't use it. Skip to next one.
continue;
}
if(empty($image)){
// This post has no image. Skip to next one!
continue;
}
// Still with me? Time to download the image!
// But we need to make sure we can download the image first.
$isExternal = (bool)parse_url($image); // check if it's a local image or an external image.
if(!$isExternal){
// It's not external, but we can't download it without url? Let's give it an url!
if(strpos($image, "/") !== "0"){
// additional check that it's not relative to our location.
// If it is relative, we add a slash to make it absolute, but it's not quaranteed to work.
$image = "/" . $image;
}
if(is_multisite()){
// We need to check if we're running multisite, get_current_blog_id() isn't defined on single sites.
$image = get_site_url(get_current_blog_id()) . $image;
}
else{
$image = get_site_url() . $image;
}
}
// Ok, now we can download the image!
if(!$dryRun){
$tempImage = file_get_contents($image);
$uploadDir = wp_upload_dir();
$filePath = $uploadDir['path'] . "/" . basename($image);
file_put_contents($filePath, $tempImage);
// straight copypaste from https://codex.wordpress.org/Function_Reference/wp_insert_attachment
$filename = $filePath;
// The ID of the post this attachment is for.
$parent_post_id = $id;
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );
// Get the path to the upload directory.
$wp_upload_dir = $uploadDir;
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $parent_post_id, $attach_id );
// Tada. Everything *went* as expected, now delete the first image, and save the content.
$post->post_content = preg_replace($imageRegex, "", $post->post_content, 1);
wp_update_post($post);
}
else{
// Dry run! Don't actually save anything, but instead show some output.
$uploadDir = wp_upload_dir();
$filePath = $uploadDir['path'] . "/" . basename($image);
$post->post_content = preg_replace($imageRegex, "", $post->post_content, 1);
echo "Image url: " . PHP_EOL;
var_dump($image);
echo PHP_EOL;
echo "Save path: " . PHP_EOL;
var_dump($filePath);
echo PHP_EOL;
echo "Post data: " . PHP_EOL;
var_dump($post);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment