Im trying to show an ‘out of stock message’ on the single product page for products that are out of stock.
I have this code in my functions.php
function stock_catalog() { global $product; if (number_format($product->stock, 0, '', '') <= 0) { echo '<p class="mb-2"> ' . __('** Sorry currently out of stock **', 'text- domain') . '</p>'; } } add_action('woocommerce_get_availability', 'stock_catalog');
I get the following error:
Notice: stock was called incorrectly. Product properties should not be accessed directly. Backtrace: require(‘wp-blog-header.php’), require_once(‘wp-includes/template-loader.php’), include(‘/plugins/woocommerce/templates/single-product.php’), wc_get_template_part, load_template, require(‘/themes/mytheme/woocommerce/content-single-product.php’), do_action(‘woocommerce_single_product_summary’), WP_Hook->do_action, WP_Hook->apply_filters, woocommerce_template_single_add_to_cart, do_action(‘woocommerce_simple_add_to_cart’), WP_Hook->do_action, WP_Hook->apply_filters, woocommerce_simple_add_to_cart, wc_get_template, include(‘/plugins/woocommerce/templates/single-product/add-to-cart/simple.php’), wc_get_stock_html, WC_Product->get_availability, apply_filters(‘woocommerce_get_availability’), WP_Hook->apply_filters, stock_catalog, WC_Abstract_Legacy_Product->__get, wc_doing_it_wrong Please see Debugging in WordPress for more informati in /homepages/17/d825330075/htdocs/mytheme/wp-includes/functions.php on line 5313
Any ideas how to fix this issue?
Advertisement
Answer
Need to use the method “get_stock_quantity”
function stock_catalog($availability, $product) { if ( $product->managing_stock() && $product->get_stock_quantity() <= 0) { $availability['availability'] = __('** Sorry currently out of stock **', 'text- domain'); } return $availability; } add_filter('woocommerce_get_availability', 'stock_catalog', 10, 2);
More details https://woocommerce.github.io/code-reference/classes/WC-Product.html#method_get_stock_quantity