Created
December 7, 2013 20:14
-
-
Save micahwave/7848034 to your computer and use it in GitHub Desktop.
Fix featured images
This file contains hidden or 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
/** | |
* | |
*/ | |
function fix_featured_images() { | |
// only do 10 at a time | |
$posts = get_posts( array( | |
'posts_per_page' => 10, | |
'post_status' => 'publish', | |
'meta_query' => array( | |
array( | |
'key' => '_thumbnail_id', | |
'compare' => 'NOT EXISTS', | |
'value' => 'http://core.trac.wordpress.org/ticket/23268' | |
), | |
array( | |
'key' => '_processed_post', | |
'compare' => 'NOT EXISTS', | |
'value' => 'http://core.trac.wordpress.org/ticket/23268' | |
) | |
) | |
)); | |
$cnt = 0; | |
if( $posts ) { | |
foreach( $posts as $post ) { | |
// consider the post processed | |
update_post_meta( $post->ID, '_processed_post', 1 ); | |
if( empty( $post->post_content ) ) | |
continue; | |
$doc = new DomDocument(); | |
$doc->loadHTML( $post->post_content ); | |
$img = $doc->getElementsByTagName( 'img' )->item( 0 ); | |
if( $img ) { | |
$url = $img->getAttribute( 'src' ); | |
$tmp = download_url( $url ); | |
preg_match( '/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $url, $matches ); | |
if ( is_wp_error( $tmp ) ) { | |
@unlink($file_array['tmp_name']); | |
$file_array['tmp_name'] = ''; | |
continue; | |
} | |
$file_array = array( | |
'name' => basename( $matches[0] ), | |
'tmp_name' => $tmp | |
); | |
$thumbnail_id = media_handle_sideload( $file_array, $post->ID, null ); | |
if( $thumbnail_id && !is_wp_error( $thumbnail_id ) ) { | |
update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id ); | |
$cnt++; | |
} | |
} | |
} | |
die( 'Fixed ' . $cnt . ' posts.' ); | |
} | |
} | |
add_action( 'admin_init', 'fix_featured_images' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment