I’m trying to just show stock on a single product when a user is logged in. I’ve tried manipulating two different scripts I’ve found, but it’s not working. Please help!
function show_stock() {
global $product;
if ( $product->get_stock_quantity() ) { // if manage stock is enabled
if ( number_format($product->get_stock_quantity(),0,'','') < 3 ) { // if stock is low
echo '<div class="remaining">Only ' . number_format($product->get_stock_quantity(),0,'','') . ' left in stock!</div>';
} else {
echo '<div class="remaining">' . number_format($product->get_stock_quantity(),0,'','') . ' left in stock</div>';
}
}
}
add_action('woocommerce_after_shop_loop_item','show_stock', 10);
add_action( 'init', 'hide_stock_not_logged_in' );
function hide_stock_logged_in() {
if ( !is_user_logged_in() ) {
remove_action('woocommerce_after_shop_loop_item','show_stock', 10);
}
}
2
Answers
You may,
1- Use wp_footer hook, which is called every page load
2- Check if user logged in inside this hook
3- If no, just make “display:none” for css attributes (class or id) of stock item.
Example:
You may need to change the “style” part. Tested and works fine. I hope this will help you.
@MrEbabi ‘s solution is perfect but as an alternative you could also just use css like so: