Categories
WooCommerce

Add a Custom Placeholder Image for WooCommerce Products

WooCommerce has a default placeholder for all products that don’t have images set. Here’s what it currently is set to:

Default WooCommerce Placeholder Image

I actually like it quite a lot, but it might not always be the most useful thing to show for your specific store.

If you want to change the default placeholder for your WooCommerce store, it’s not too complicated. Let’s walk through what has to happen:

The Source

I like to cover what code we’re working with first. If you do this regularly you’ll eventually be able to do this on your own šŸ™‚

WooCommerce: 4.5.2
Filter: woocommerce_placeholder_img_src
Source: https://github.com/woocommerce/woocommerce/blob/4.5.2/includes/wc-product-functions.php#L303

Working through the logic

The function, wc_placeholder_img is where the placeholder images are loaded from, so looking at that function, we can see that it checks for:

  • The woocommerce_placeholder_image option being set to a specific image ID
  • If that option is not set, it calls the wc_placeholder_img_src
  • wc_placeholder_img_src function then calls the filter, woocommerce_placeholder_img_src, that lets us change the image source for the placeholder!

Our code should then:

  • Set the ID for the image we want to be the new placeholder
  • Make sure we set the option to the right image if we need to
  • Return the right image source only if the option is not set

Here’s the code:

<?php // only add this first line if your file already does not have it

/**
 * Change the default placeholder image
 */
add_filter('woocommerce_placeholder_img_src', 'custom_woocommerce_placeholder_img_src', 10);

function custom_woocommerce_placeholder_img_src( $src ) {
	
	// Set your new Placeholder Image ID here
	$new_image_id = 400;

	// Update the woocommerce_placeholder_image option
	$current_placeholder_id = get_option( 'woocommerce_placeholder_image' );
	if ( $current_placeholder_id !== 0 || $current_placeholder_id !== $new_image_id ) {
		update_option( 'woocommerce_placeholder_image', $new_image_id );
	} else {
		// Set the Image SRC
		$src = wp_get_attachment_url( $new_image_id );

	}
	return $src;
}

Make sure you upload the Image and grab the ID for that image for that code to work. If you’re not what the Image ID is, go to the Media Library and click on the image. Then, in the address bar you should see the ID like this:

The ID is 400 for this image

Tested on

WooCommerce 4.5.2 ✔
Storefront 2.7.0 ✔

That’s it! If you have any questions or suggestions for how to improve this, please leave a comment.

Leave a Reply