Automatically apply WooCommerce featured image if it is missing.
If you‘re running a WooCommerce store, it‘s important to have good product images.
Unfortunately, sometimes product images go missing, leaving you with a blank space on your product page. There are a few ways to automatically set a featured image for your product if the image is missing. One way is to use a custom code. With this code, you can automatically set a featured image for your product from one of the product‘s variations. This is helpful if you have products with multiple variations and you want to ensure that there‘s always a featured image. Next we are going to add some custom code to your functions.php file. This is a bit more technical, but it‘s not too difficult to do. Here‘s the code you‘ll need to add to your functions.php file:
// Author: WooBend
// Needed functionality: Automatically apply first variation image as product featured image, if the image is missing while creating a product
add_action( 'woocommerce_process_product_meta', 'woo_add_featured_image_to_product', 10, 2 );
function woo_add_featured_image_to_product($post_id, $post)
{
switch ($post->post_type) :
case "product" :
if ( !has_post_thumbnail( $post->ID ) ) :
$attached_image = get_posts( array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'numberposts' => 1,
'post_parent' => $post->ID
) );
if ( $attached_image ) :
$attachment_id = $attached_image[0]->ID;
set_post_thumbnail( $post->ID, $attachment_id );
endif;
endif;
break;
endswitch;
}
How to edit functions.php file in WordPress to add custom code
To access your functions.php file, you‘ll need to connect to your WordPress site via FTP. Second way is to download and activate a “File Manager” plugin. Once you‘re connected, navigate to the /wp–content/themes/your–theme–folder/ folder. In this folder, you should see your functions.php file. Once you‘ve located your functions.php file, you can download it to your computer and edit it in a text editor like Notepad++ or Sublime Text. When you‘re done making your changes, save the file and upload it back to your WordPress site. Be sure to upload it to the same location that you downloaded it from. And that‘s it! You‘ve successfully edited your WordPress functions.php file.