In/Out of Stock Custom Messages

What if you would like to show a certain text in a tab when stock is available and another when there is no stock. Well we could add a shortcode with an attribute, one with in stock and another without out of stock. But we would prefer to use one. One loading all text with an if else statement. But that would mean all text would be in the plugin or functions.php.

to add a shortcode we can use

/**
 * Register in or out of stock text shortcode
 *
 * @return null
 */
function imwz_register_in_or_out_stock_text_shortcode() {
  add_shortcode( 'inoroutofstocktext', 'imwz_in_or_out_stock_text_check' );
}
add_action( 'init', 'imwz_register_in_or_out_stock_text_shortcode' );

Now, the actual function with text and if else statement would be like:

function imwz_in_or_out_stock_text_check () {
  global $product;
  
  ob_start();

  $output = '';

  if ( ! $product->managing_stock() && ! $product->is_in_stock() ) {
      echo "2-4 dagen";
  }
  elseif ($product->is_in_stock()) {
    echo "1-2 dagen";
  }

  else {
    echo "nothing to see here"; // or return
  }

  $output = ob_get_clean();
  // wp_reset_postdata();
  
  return $output;
}

For a live warning when adding more items to the cart than there are in stock see a jQuery solution at https://stackoverflow.com/questions/54452789/how-can-i-display-text-message-if-woocommerce-quantity-input-is-greater-than-sto as well as https://wordpress.org/plugins/woocommerce-cart-stock-reducer/ . Both just not solutions we want to use now due to many database requests.

No comment yet, add your voice below!


Add a Comment

Your email address will not be published. Required fields are marked *