skip to Main Content

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


  1. 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:

    function hide_stock_if_user_not_logged_in()
    {
        if ( !is_user_logged_in() )
        {
            echo "<style>p.stock.in-stock { display: none }</style>";
        }
    }
    add_action( 'wp_footer', 'hide_stock_if_user_not_logged_in' );
    

    You may need to change the “style” part. Tested and works fine. I hope this will help you.

    Login or Signup to reply.
  2. @MrEbabi ‘s solution is perfect but as an alternative you could also just use css like so:

    .logged_in .remaining{
    display:none;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search