Created
August 28, 2011 19:40
-
-
Save chrisguitarguy/1177118 to your computer and use it in GitHub Desktop.
Programmatically update WordPress post thumbnails from old style custom fields with URLs
This file contains 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 | |
/* | |
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