Skip to content

Instantly share code, notes, and snippets.

@marushu
Created September 18, 2015 08:31
Show Gist options
  • Save marushu/1ed48226a2a13660917c to your computer and use it in GitHub Desktop.
Save marushu/1ed48226a2a13660917c to your computer and use it in GitHub Desktop.
<?php
$args = array(
'post_type' => 'news',
'posts_per_page' => -1,
);
$set_all_news_posts = get_posts( $args );
foreach( $set_all_news_posts as $post ) {
setup_postdata( $post );
delete_post_thumbnail( $post );
if ( preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches) ) {
$image_url = $matches[1][0];
}
//var_dump( $image_url );
// no thumbnail? on to the next
if( empty( $image_url ) ) continue;
// find mime type for later
$filetype = wp_check_filetype( $image_url );
if( has_post_thumbnail() ) {
// Set up an array of args new attachment
$args = array(
'post_mime_type' => $filetype['type'],
'post_title' => esc_attr( $post->post_title ), // you may want something different here
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment!
$thumb_id = wp_insert_attachment( $args, $image_url, $post->ID );
// gotta set up some meta data (height, width, etc)
// must include this path
require_once(ABSPATH . 'wp-admin/includes/image.php');
$metadata = wp_generate_attachment_metadata( $thumb_id, $image_url );
wp_update_attachment_metadata( $thumb_id, $metadata );
// set post thumbnail :)
update_post_meta( $post->ID, '_thumbnail_id', $thumb_id );
}
}
wp_reset_postdata();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment