Reputation: 466
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?
Upvotes: 1
Views: 1388
Reputation: 469
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
Upvotes: -1
Reputation: 29624
Your code contains not 1 but several errors
woocommerce_get_availability
is not an action but a filter hooknumber_format()
does not apply here at all$product->stock
needs to be replaced with $product->get_stock_quantity()
managing_stock()
must be true, otherwise there is no possibility to set/store a product stock quantity$availability
$product
is passed as an argument to the function, so there is no need to use a global variableSo you get:
// Change stock text
function filter_woocommerce_get_availability( $availability, $product ) {
// Managing stock is activated
if ( $product->managing_stock() ) {
// Stock quantity
$stock_quantity = $product->get_stock_quantity();
// Stock quantity is less than or equal to 0
if ( $stock_quantity <= 0 ) {
$availability['availability'] = __( 'Sorry currently out of stock', 'woocommerce' );
}
}
return $availability;
}
add_filter( 'woocommerce_get_availability', 'filter_woocommerce_get_availability', 10, 2 );
Upvotes: 3