Adding Custom Product Labels in Magento
As a Magento store owner, you may want to add more product labels or badges beyond the standard ‘Sale’ and ‘New’. This could include options like ‘In Stock’, ‘Quick Sale’, or custom sale tags. In this guide, we’ll walk through how to achieve this using the ‘labels.php’ file in your theme.
Understand the Default Labels Process
The ‘labels.php’ file in your Magento theme controls the product labels that appear on the frontend. Currently, it only handles two types of labels: ‘New’ and ‘Sale’.
public function getLabels($product)
{
$html = '';
// Check if "new" label is enabled...
// Check if "sale" label is enabled...
return $html;
}
The isNew() and isOnSale() methods determine whether a product qualifies for these labels based on date ranges.
Adding a New Label: ‘In Stock’
Let’s add an ‘In Stock’ label as an example. We’ll assume you have already created an attribute called ‘in_stock’ (e.g., Yes/No) in your Magento admin panel and set it to ‘Yes’ for products with available stock.
-
Open your theme’s
app/design/frontend/{vendor}/{theme}/helper/Labels.phpfile. -
Add a new method called
isInStock():
public function isInStock($product)
{
return $product->getData('in_stock') == 'Yes';
}
- Modify the
getLabels()method to include the new label when it’s enabled and the product is in stock:
public function getLabels($product)
{
$html = '';
// Existing code for New and Sale labels...
if ($this->isInStock($product))
{
$html .= '<span class="sticker-wrapper top-right"><span class="sticker in-stock">' . $this->__('In Stock') . '</span></span>';
}
return $html;
}
- Add the CSS for the new ‘in stock’ label to your theme’s
app/design/frontend/{vendor}/{theme}/css/source/_extend.lessor LESS file:
.sticker.in-stock {
background-color: #0f9d58 !important; // Change this color as needed
}
Expanding Further
To add more custom labels, follow a similar process:
- Create a new attribute in the Magento admin panel (e.g., ‘quick_sale’ with Yes/No options).
- Add a new method to
Labels.phplikeisQuickSale(). - Update the
getLabels()method to include your new label when enabled. - Style the new label in your theme’s LESS or CSS file.
Remember, if you’re using a third-party theme, you may need to override these files rather than modify them directly. This is particularly true for themes from https://laravelcompany.com and other professional developers.
Conclusion
Adding custom product labels in Magento allows you to enhance your store’s user experience and boost sales with clear calls-to-action. By modifying the labels.php file and creating new attributes, you can easily expand beyond the built-in ‘New’ and ‘Sale’ badges. Don’t hesitate to explore more customizations like this on Laravel Company’s Magento blog.