When I moved my house to nguyenvanquan7826.com, I had a problem in importing data, all photos i uploaded missing. I can’t spend all day to download and set featured image for all articles. Fortunately, almost images in the articles I uploaded to imgur.com and post it later, so they are still there.I tried to find way to get these images in article to set it as thumbnail image and I found two ways.
Option 1: Use the code
First, you copy the below function into function.php file:
function get_first_image() { global $post, $posts; $first_img = ''; ob_start(); ob_end_clean(); $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); $first_img = $matches[1][0]; if(empty($first_img)) { $first_img = "/path/to/default.png"; } return $first_img; }
Then open index.php file (or content.php) and find the function which calls old images, most of them use function the_post_thumbnail()
. With me, it is:
<?php if ( has_post_thumbnail() ) { ?> <?php echo '<div class="featured-thumbnail">'; the_post_thumbnail('featured',array('title' => '')); echo '</div>'; ?> <?php } ?>
Replace it by:
<img src="<?php echo get_first_image(); ?>" alt="<?php the_title(); ?>" />
It will effects on home page, you can set on tag, search or category into archive.php file, category.php file, tag.php file.
Option 2: Use plugin
You can use plugin External URL To Post Thumbnail. However, i haven’t ever used that way so if you use, please tell me about it!