skip to Main Content

How is it possible to hide a shortcode conditionally on WooCommerce single product pages if stock is empty?

For example if a product is out of stock:

  • The shortcode [scale-prices] should disappear
  • (A green traffic light picture changes to a yellow traffic light picture)

2

Answers


  1. You can use any of these single product page hooks and add a condition of your need.

    https://www.businessbloomer.com/woocommerce-visual-hook-guide-single-product-page/

    Like you can use woocommerce_before_single_product and check for product availablity and based on that result you can use add_shortcode, remove_shortcode. Also you can add script using wp_footer script if required.

    You can share further details/scenario for exact solution.

    Login or Signup to reply.
  2. Your question is quite broad. But you could add a CSS body class to the product page if a product (or a variation) is out of stock. You can then use that to manipulate your page for instance via CSS or JavaScript.

    The following code snippet will add out-of-stock as a body class for a simple out of stock product, and a {variation-id}-out-of-stock body class for each variation that is out of stock:

    add_filter( 'body_class', 'add_class_if_product_is_out_of_stock', 10, 1 );
    function add_class_if_product_is_out_of_stock( $classes ) {
    
        if ( is_product() ) {
    
            global $post;
    
            if ( $product = wc_get_product( $post->ID ) ) {
                if ( $product->is_type( 'variable' ) ) {
                    $children = $product->get_children();
                    foreach ( $children as $child_id ) {
    
                        if ( $product = wc_get_product( $child_id ) ) {
                            if ( $product->is_in_stock() == false ) {
                                $classes[] = sprintf( '%s-out-of-stock', $child_id );
                            }
                        }
                    }
                } elseif ( $product->is_in_stock() == false ) {
                    $classes[] = 'out-of-stock';
                }
            }
    
        }
        return $classes;
    }
    

    This snippet should be added to the functions.php of your child theme or via a plugin like Code Snippets.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search