Reputation: 173
I'm adding a new stock status in WooCommerce products. It has been done by the help of How to add custom stock status to products in WooCommerce 4+ answer code.
But the problem is that when the price field of products is empty it doesn't show the status (front-end). but otherwise when the product has the price, it shows the status.
What can I do, to make the status be shown even if the price field is empty?
Upvotes: 0
Views: 2278
Reputation: 29614
You will see that if the price is empty, besides not showing the product stock status, the price (the HTML code) for this will also not be displayed. Because the product is considered as not purchasable if the price is empty.
So in order to display the product stock status, you should make the product purchasable, if the price is empty. However, I do not believe this is your intention?
So instead of focusing on displaying the product stock status, it will be much simpler to display something else (HTML/text) where the price is normally displayed,
and that can be done by using the woocommerce_empty_price_html
filter hook
function filter_woocommerce_empty_price_html( $html, $product ) {
// NOT true on a single product page, RETURN
if ( ! is_product() ) return $html;
// Add HTML
$html = '<p>My text</p>';
return $html;
}
add_filter( 'woocommerce_empty_price_html', 'filter_woocommerce_empty_price_html', 10, 2 );
function filter_woocommerce_empty_price_html( $html, $product ) {
// NOT true on a single product page, RETURN
if ( ! is_product() ) return $html;
// Get stock status
$product_stock_status = $product->get_stock_status();
// Compare
if ( $product_stock_status == 'MY CUSTOM STATUS' ) {
// Add HTML
$html = '<p>My text based on product stock status</p>';
}
return $html;
}
add_filter( 'woocommerce_empty_price_html', 'filter_woocommerce_empty_price_html', 10, 2 );
The only downside to this solution(s) is that your new HTML/text will not be displayed where you normally see the product stock status, but where the price is normally displayed.
Upvotes: 4