Support » Plugin: WooCommerce » Disable single product page for out-of-stock products

  • Resolved karl19

    (@karl19)


    I’ve set out-of-stock items to be hidden under settings > products > inventory, this still made them show up in searches though, so I used this function instead https://iconicwp.com/blog/hide-stock-products-woocommerce-catalog-pages/, which works well.

    The one issue I’m having is that I don’t want to show out-of-stock products at all, not even single product pages. Setting a product to visibility private does this, but we’re having some other conflicts when using visibility, so would rather use out-of-stock (as this better represents the product status anyway).

    Does anyone know of a function where we can hide single product pages if they’re out-of-stock? I guess we could check for stock-status and then do a header redirect, but perhaps there is something simpler and more native to WooCommerce?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Try This:

    
    /**
    * Retrieve a product given its slug.
    */
    function get_product_by_slug($page_slug) {
        global $wpdb;
            $product = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s", $page_slug, 'product'));
            if ( $product )
                return wc_get_product($product);
        return null;
    }
    
    function redirect_out_of_stock_product( $query ) {
    
    	if( !is_admin() && $query->is_main_query() && $query->query['post_type'] === 'product' ){
    		$product = get_product_by_slug($query->query['name']);
    		if( !$product->is_in_stock() ){
    			wp_redirect( 'https://example.com/some/page' );
    		}
    	}
    
    }
    add_action( 'pre_get_posts', 'redirect_out_of_stock_product' );
    • This reply was modified 1 year, 8 months ago by  Isu.

    Hi Isu, many thanks for your reply and sorry for the delay in replying, holiday times. Have tried your code and it seems to work fine, now re-directed out-of-stock items to the homepage.

    Many thanks for your input, much appreciated!!

    Hi Isu, i have the same issue of karl19. I’d like to disable the single product page when it goes “Out of Stock”, but without redirect. I mean if the product is not available in stock and I try clicking on it, nothing must happen (as if the product were an image)

    I’ve tried to use the code above, but the shop page shown me an error message, referring to the line “if( !$product->is_in_stock() ){”

    Can you help me?
    Thanks in advance

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Disable single product page for out-of-stock products’ is closed to new replies.