Search code examples
magentomagento2

Magento 2: Switch the price for 'Sold' label after product is out of stock


I'm trying to to switch the price for a 'Sold' label on the product page of products that are out of stock. If a product is sold out, the price should be hidden and in its stead should be a 'Sold' label.

I figured out that the price is placed in catalog_product_view.xml and it calls upon the vendor/magento/module-catalog/view/base/templates/product/price/final_price.phtml file, but I could not figure out where and how to bring in a condition to check whether product is sold out or not.


Solution

  • As I understand you have two parts to this issue

    1) Hide price on Product-detail page if product is Out-of-stock

    • Prices are defined in vendor/magento/module-catalog/view/frontend/layout/catalog_product_view.xml
    • called at class: Magento\Catalog\Pricing\Render and method: _toHtml()
    • You can override the method using DI to below

      
          protected function _toHtml()
          {
              /** @var PricingRender $priceRender */
              $priceRender = $this->getLayout()->getBlock($this->getPriceRender());
              if ($priceRender instanceof PricingRender) {
                  $product = $this->getProduct();
                  if ($product instanceof SaleableInterface && $product->isAvailable()) {
                      $arguments = $this->getData();
                      $arguments['render_block'] = $this;
                      return $priceRender->render($this->getPriceTypeCode(), $product, $arguments);
                  }
              }
              return parent::_toHtml();
          }
      
    • $product->isAvailable() is the new condition that we have added

    2) Show Sold label

    • outofstock label is shown by default, but if you still want to show create your block & template in vendor/magento/modul-catalog/view/frontend/layout/catalog_product_view.xml

      • and $product->isAvailable() function to check product's availability

    Hope this helps