WooCommerce Variable Products – If Missing Main Image, Show Variable Item Featured Image


About The Author
Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







WooCommerce Variable Products – If Missing Main Image, Show Variable Item Featured Image

Here’s an interesting request and code snippet to go along with it. I had a client who was using the WooCommerce to LightSpeed Retail Point of Sale Plugin developed by WooThemes. Until about two days ago, the plugin had a bug that would remove the master products featured image if the product was variable. Basically, all the child (variable) products would have an image assigned to them, but the main master product would be missing the featured image.

This caused major issues as the majority of the clients products were variable so their store consisted of a bunch of missing images in terms of archive pages.

The solution was obvious, provide an IF statement that checked to see if a variable product child products consisted of an image. If so, display that image rather than an empty image.

Below is how we achieved it with notes added in for clarity:

<?php
// check to see if a product has a featured image
if ( has_post_thumbnail() ) {
echo get_the_post_thumbnail( get_the_ID(), 'shop_catalog', array( 'class' => 'img-responsive' ) );
// it doesn't so let's check if the product is the variable type
} elseif($product->is_type( 'variable')) {
	$variations = $product->get_available_variations();
	foreach($variations as $variation) {
// now we're going to look through each variation until we find a featured image
		$varid = $variation[variation_id];
		$varimage = get_the_post_thumbnail( $varid, 'shop_catalog', array( 'class' => 'img-responsive' ) );
						if(!empty($varimage)) {
// we've found a variable product with a featured image, let's display it and break the loop
	echo $varimage;
	break;
}
} ?>
<!-- If we don't find anything, we'll just display an empty image-->
<img src="<?php echo get_template_directory_uri(); ?>/assets/images/coming-soon.jpg" class="img-responsive">
<?php } else { ?>
<!-- else, we're displaying a not found image -->
<img src="<?php echo get_template_directory_uri(); ?>/assets/images/coming-soon.jpg" class="img-responsive">
<?php } ?>

Share Your Thoughts

Leave a Reply

Your email address will not be published.


Related Stuff You Might Like







WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!