Menu Close

WooCommerce: Display Stock Status For External Products

default

By default, WooCommerce external products do not have and do not display any stock, as they are simple redirects to an external URL. This may be unfortunate, because before clicking on an external URL and send people away from your website, you may want to make sure the current item is in stock (so that you have more chances to convert the sale and earn a referral commission, if that’s your business model).

So, how do we “manage stock” for an external product, and display the stock status on the single product page, just before the “Buy Product” button?

I’m now able to show the stock status for WooCommerce external/affiliate products as well! Just store the status in a custom field, and the snippet below will do the rest.

PHP Snippet: Show Stock Availability @ WooCommerce Single External Product Page

Before you use the snippet below, you first need to “set” the external product stock status via a custom field that we’ll call “extstock“. I set its value to either 1 (in stock) or 0 (out of stock). You can of course rename it to whatever you want it, redefine values, use it as stock quantity as opposed to stock status, and even “get” it from another custom field defined by a plugin:

I’m on the single product page for an external product, and I’ve just manually added a new custom field called “extstock” with a value of 1. I will need this in the snippet below to find out the stock status, so that I can display it on the frontend.
/**
 * @snippet       External Product Stock Status @ WooCommerce Single Product
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 7
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

add_action( 'woocommerce_external_add_to_cart', 'bbloomer_external_product_stock', 29 );

function bbloomer_external_product_stock() {
	global $product;
	$stock_status = get_post_meta( $product->get_id(), 'extstock', true );
	if ( ! $stock_status ) return;
	if ( $stock_status == 1 ) {
		$availability = __( 'In stock', 'woocommerce' );
		$class = 'in-stock';
	} else {
		$availability = __( 'Out of stock', 'woocommerce' );
		$class = 'out-of-stock';
	}
	wc_get_template(
		'single-product/stock.php',
		array(
			'product'      => $product,
			'class'        => $class,
			'availability' => $availability,
		)
	);
}
View Source
Posted in WooCommerce Tips