Skip to content

Instantly share code, notes, and snippets.

@bvandreunen
Created December 15, 2013 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bvandreunen/7970575 to your computer and use it in GitHub Desktop.
Save bvandreunen/7970575 to your computer and use it in GitHub Desktop.
In WordPress, takes a url from a custom field and turns it into a thumbnail ID. Found here: http://pastie.org/2386814
<?php
/*
Plugin Name: Update thumbnails
Plugin URI: http://pmg.co
Description: Takes a url from a custom field and turns it into a thumbnail ID
Version: .01
Author: Christopher Davis
Author URI: http://pmg.co/people/chris
*/
/**
* CHANGE THESE!
*/
define( 'OLD_THUMB_KEY', 'your_thumb_key' );
define( 'DELETE_OLD_THUMB', false );
/**
* Uncomment the next line to run the above function on plugin activation.
*/
//register_activation_hook( __FILE__, 'wpse26138_set_new_thumbs' );
/* Stop editing here
-----------------------------------------*/
function wpse26138_set_new_thumbs()
{
// get an array of all the posts
$posts = get_posts(
array(
'numberposts' => -1,
'post_type' => 'post'
)
);
// bail if our get_posts() call failed
if( empty( $posts ) ) return;
// Loop through the posts
foreach( $posts as $p )
{
$image_url = get_post_meta( $p->ID, OLD_THUMB_KEY, true );
// no thumbnail? on to the next
if( empty( $image_url ) ) continue;
// find our mime type for later
$filetype = wp_check_filetype( $image_url );
// Set up an array of args for our new attachment
$args = array(
'post_mime_type' => $filetype['type'],
'post_title' => esc_attr( $p->post_title ), // you may want something different here
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment!
$thumb_id = wp_insert_attachment( $args, $image_url, $p->ID );
// gotta set up some meta data (height, width, etc)
// the functions are in this file, so we have to include it
require_once(ABSPATH . 'wp-admin/includes/image.php');
$metadata = wp_generate_attachment_metadata( $thumb_id, $image_url );
wp_update_attachment_metadata( $thumb_id, $metadata );
// Finally! set our post thumbnail
update_post_meta( $p->ID, '_thumbnail_id', $thumb_id );
if( DELETE_OLD_THUMB )
delete_post_meta( $p->ID, OLD_THUMB_KEY );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment