• Home
    • Cool Knowledge base
    • Light Knowledge base
    • Help Desk
    • OnePage Documentation
  • Services
    • Main Services
    • PPC Services
    • SEO Services
    • SMM Services
  • Docs
  • Blog
    • Affiliate
    • Ecommerce
    • Frontend
    • linux
      • nginx
    • PHP
      • Magento
      • wordpress
    • Python
    • SEO
    • Web
  • Forum
    • Forums
    • Forum Topics
    • Topic Details
    • Ask Question
  • Pages
  • Contact

Subscribe to Updates

Get the latest creative news from FooBar about art, design and business.

What's Hot

VideoJS – multiple source demo

2022-03-08

Add custom field to Woocommerce tab

2022-03-07

Surror Product Tabs for WooCommerce

2022-03-07
Facebook Twitter Instagram
  • 中文
  • English
Facebook Twitter Instagram Pinterest VKontakte
SEO & Website build tips SEO & Website build tips
  • Home
    • Cool Knowledge base
    • Light Knowledge base
    • Help Desk
    • OnePage Documentation
  • Services
    • Main Services
    • PPC Services
    • SEO Services
    • SMM Services
  • Docs
  • Blog
    • Affiliate
    • Ecommerce
    • Frontend
    • linux
      • nginx
    • PHP
      • Magento
      • wordpress
    • Python
    • SEO
    • Web
  • Forum
    • Forums
    • Forum Topics
    • Topic Details
    • Ask Question
  • Pages
  • Contact
SEO & Website build tips SEO & Website build tips
Home»wordpress»Automatically Set the First Post Image as a Featured Image in WordPress
wordpress

Automatically Set the First Post Image as a Featured Image in WordPress

OxfordBy Oxford2019-09-29No Comments6 Mins Read
Facebook Twitter Pinterest LinkedIn Tumblr Email
WordPress functions php file
Share
Facebook Twitter LinkedIn Pinterest Email

Have you ever run into the situation where you have a lot of posts without a featured image and you need to change that to be able to use WordPress Themes which depend upon featured images in their layout? We’ve got a simple solution to this problem.

WordPress functions php file

Everyone likes to change up their WordPress site every once in a while, whether its by adding new plugins to expand the functionality, or getting a brand-new look with a fresh theme. Such changes don’t always go smoothly though; implementing a new plugin or theme can bring its own set of issues; for example, what if you make the jump to a new theme, but its layout relies upon featured images from posts to deliver its content while your previous theme did not? You could be left with hundreds of posts that don’t have a featured image assigned, which leaves you with the frustrating task of going through each post one-by-one and assigning a Featured Image via the Edit Post screen, wasting several hours in the process.

So what can you do if you’ve got a lot of posts without a featured image, and you need to change that ASAP so you can use your new featured-image-based theme? If you have a thing for tedium then you could of course do things manually, but we’ve got a much simpler solution that will take a lot of the sting out of this task.

The Featured Image generator function

The script below will be able to take care of your image problem, and all you’ll need to do is copy the code and add it into your theme’s functions.php file:

function auto_featured_image() {
    global $post;
 
    if (!has_post_thumbnail($post->ID)) {
        $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
         
      if ($attached_image) {
              foreach ($attached_image as $attachment_id => $attachment) {
                   set_post_thumbnail($post->ID, $attachment_id);
              }
         }
    }
}
// Use it temporary to generate all featured images
add_action('the_post', 'auto_featured_image');
// Used for new posts
add_action('save_post', 'auto_featured_image');
add_action('draft_to_publish', 'auto_featured_image');
add_action('new_to_publish', 'auto_featured_image');
add_action('pending_to_publish', 'auto_featured_image');
add_action('future_to_publish', 'auto_featured_image');

Inserting the function into your theme

Don’t worry if you’re not familiar with adding scripts to your WordPress theme’s files as it’s a very simple process. There are two main options for adding the script to the functions.php file; first, you can use FTP to connect to your server, download the functions file, make your changes and then reupload the file, replacing the original, or you can utilize the editor that is built into WordPress to access and change the file directly in the WordPress dashboard.

Using FTP

The FTP method might seem long-winded, but if you’re familiar with the concept and how to use it then it’s actually an extremely fast and accurate solution. If you’re not sure where to start with FTP, you can our Beginner’s Guide to FTP blog article to get the lowdown on what it does and how. Once you’re ready to go, then just follow these basic steps:

  1. Connect to your server via FTP and navigate to your current theme’s folder, which you’ll find in wp-content → themes in your WordPress installation. Make sure to open the correct folder for your theme, as every theme has its own functions.php file and adding the script to the wrong, inactive theme won’t do you any favours!
  2. Download the existing functions.php file from the theme folder, and open it in the code/text editor of your choice (we like to use the Sublime Text code editor, but whatever you’re comfortable with will do).
  3. Copy the entire code provided above and paste it at the end of the functions.php file’s code. Save the changes.
  4. With the file now modified accordingly, connect to your server via FTP once again and upload the updated file to the theme folder, replacing the original. You’re now ready to go!

Using the WordPress Editor

The WordPress Editor allows an admin to modify the core theme files in the dashboard without the need for FTP access; an elegant solution if you’re not comfortable with FTP and just need a quick solution. Making the changes with this method is very easy:

  1. In the WordPress Dashboard, click on Appearance → Editor in the left menu to open the editor screen.
  2. You’ll now be on the Edit Themes page for your current active theme; a list of theme files is on the right, and the code to be modified will appear in the main editor window. Under the Templatesheading of the theme file list, look for the functions.php file and click on it to open it in the editor.
  3. You can now see the code of the functions.php file in the main window of the editor; scroll down to the end of the file and then copy and paste the script above at the end of the existing code.
  4. Now click on the Update File button under the editor to save changes; the code is now ready!

How the script works

So you’ve added the script to your functions file; now what is it actually going to do? It’s really very simple; whenever a post is viewed or a new post saved, the script checks the specific post to see if it has a featured image set. If not, then the script checks for others images in the post, grabs the first one it find, and sets this image as the featured image.

Something to be aware of here is that this instruction will be executed every time a post is displayed, which can have a slight performance hit on your website. For this reason, we recommend removing the following lines of code from the function once all of the featured images have been generated for existing articles:

1
2
// Use it temporary to generate all featured images
add_action('the_post', 'auto_featured_image');

There are two other important takeaways from this:

The featured image must be removed from the media manager, and each image may only be automatically added as a featured image once. That means if you’ve already used a particular image as a featured image in a post, any future posts that use the same image will not be able to automatically use it as the featured image. For this reason we recommend using this solution only to migrate your older posts across to the updated format; once this is done and all earlier articles have been updated, the featured image can be manually set for any new posts as this method allows for duplicates if needed.

Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
Avatar photo
Oxford

Related Posts

Add custom field to Woocommerce tab

2022-03-07

Surror Product Tabs for WooCommerce

2022-03-07

make wordpress static with gatsby

2021-09-29

WP Remote Users Sync – manage multi wordpress website easy

2021-08-01
Recent Posts
  • VideoJS – multiple source demo
  • Add custom field to Woocommerce tab
  • Surror Product Tabs for WooCommerce
  • How To Scrape Amazon at Scale With Python Scrapy, And Never Get Banned
  • Compile a Jekyll project without installing Jekyll or Ruby by using Docker
September 2019
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Aug   Oct »
Tags
app branding culture design digital Docly docs etc faq fashion featured fitness fix github Helpdesk Image issue leisure lifestyle magento Manual marketing memecached Photography picks planing seo sequrity tips Travel trending ui/ux web WordPress 爬虫
Editors Picks

Fujifilm’s 102-Megapixel Camera is the Size of a Typical DSLR

2021-01-05
Top Reviews
8.9

Which LED Lights for Nail Salon Safe? Comparison of Major Brands

By Oxford
8.9

Review: Xiaomi’s New Loudspeakers for Hi-fi and Home Cinema Systems

By Oxford
70

CES 2021 Highlights: 79 Top Photos, Products, and Much More

By Oxford
Advertisement
Demo
  • Facebook
  • Twitter
  • Instagram
  • Pinterest
About Us
About Us

Your source for the lifestyle news. This demo is crafted specifically to exhibit the use of the theme as a lifestyle site. Visit our main page for more demos.

We're accepting new partnerships right now.

Email Us: [email protected]
Contact: +1-320-0123-451

Facebook Twitter Instagram Pinterest YouTube LinkedIn
Recent Posts
  • VideoJS – multiple source demo
  • Add custom field to Woocommerce tab
  • Surror Product Tabs for WooCommerce
  • How To Scrape Amazon at Scale With Python Scrapy, And Never Get Banned
  • Compile a Jekyll project without installing Jekyll or Ruby by using Docker
From Flickr
Ascend
terns
casual
riders on the storm
chairman
mood
monument
liquid cancer
blue
basement
ditch
stars
© 2025 Designed by 九号资源网.

Type above and press Enter to search. Press Esc to cancel.