WordPress gets the first picture in the article as a thumbnail

If you have a large number of articles on your site, it will be a complicated step to manually set the thumbnails for each article. We shared an article “implementation method of random display of thumbnails for WordPress articles” before

WordPress realizes random display of article thumbnails. I don’t know if bloggers will forget to upload article thumbnails when updating their blog posts? Anyway, I often forget. It’s too cumbersome to manually upload thumbnails for each article, so… View the article

Today, let’s take a look at how to automatically get the first picture in the article as a thumbnail.

This will greatly reduce our workload, is indeed a very good small function, like friends can try.

//Automatically get the first picture in the article as a thumbnail
function catch_first_image() {
  global $post, $posts;
  $first_img = '';
  $output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);
  $first_img = $matches [1] [0];
  if(empty($first_img)){ //Defines a default image
    $first_img = "/wp-content/themes/um/img/default.png";
  return $first_img;

usage method

1. Add the above code to the functions.php Documents.

<?php echo catch_first_image() ?>

2. Add the above code to the article loop that needs to get the thumbnail.

Related Article
Two methods of automatically renaming uploaded files in WordPress

When we edit and publish articles, we often upload some pictures, audio and other files. Interested webmasters will find that Read more

WordPress tutorial: adding author filtering options to the background article list

When there are multiple users publishing articles in our site, in order to facilitate the administrator to view the article Read more

WordPress displays the registration time of the login user in the frontend

When using WordPress to build a website, some users want to display the user registration time in the frontend, but Read more

WordPress adds the number of SQL queries at the bottom

An excellent woodpress theme is definitely that the less SQL consulting is used, the better. How can we see how Read more

Leave a Reply

Your email address will not be published. Required fields are marked *

To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image