首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Magento 產品標籤自定義:新品 NEW、折扣百分比標籤模板實現

     編輯:PHP 相關知識

需求分析

  • 產品設置「新品起始/結束日期」時,前台顯示「NEW」標籤
  • 產品設置「特價起始/結束日期」且特價 < 原價時,顯示折扣百分比(如 -20%)
  • 標籤定位在產品圖片左上角,樣式可自定義

模板文件修改

編輯 app/design/frontend/your_package/your_theme/template/catalog/product/list.phtml(列表頁)或 view.phtml(詳情頁)。

核心代碼插入位置

在 <?php // Grid Mode ?> 註釋後,或產品圖片 <img> 標籤外層容器內。

<?php
// 獲取當前時間戳
$now = Mage::getModel('core/date')->timestamp(time());

// ---------- NEW 標籤 ----------
$newsFrom = strtotime($_product->getNewsFromDate());
$newsTo   = strtotime($_product->getNewsToDate());

// 邏輯:有開始時間 且 (未結束 或 無結束時間但已開始)
if ($newsFrom > 0 && ($now < $newsTo || ($now > $newsFrom && !$newsTo))): ?>
    <div class="ico_new_bg">NEW</div>
<?php endif; ?>

// ---------- 折扣百分比標籤 ----------
$specialFrom = strtotime($_product->getSpecialFromDate());
$specialTo   = strtotime($_product->getSpecialToDate());
$specialPrice = $_product->getSpecialPrice();
$regularPrice = $_product->getResource()->getAttribute('price')->getFrontend()->getValue($_product);

if ($specialPrice && $specialPrice < $regularPrice) {
    // 判斷特價生效時間
    if ($specialFrom > 0 && ($now < $specialTo || ($now > $specialFrom && !$specialTo))): 
        $percent = round(100 - 100 * $specialPrice / $regularPrice, 2);
    ?>
        <div class="ico_percent_bg">-<?php echo $percent ?>%</div>
    <?php endif; ?>
<?php } ?>

CSS 樣式 skin/frontend/your_package/your_theme/css/styles.css


/* 針對 Grid 模式 */
.products-grid .ico_new_bg,
.products-grid .ico_percent_bg {
    position: absolute;
    top: -10px;
    left: -10px;
    z-index: 10;
    height: 33px;
    line-height: 24px;
    padding: 0 10px;
    font-size: 14px;
    color: #ffffff;
    background: url('../images/ico_bg.png') repeat-x; /* 或純色 background: #e74c3c; */
    border-radius: 2px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

/* 確保父容器 relative 定位 */
.products-grid li.item {
    position: relative; /* 關鍵:讓 absolute 相對於此定位 */
    /* 原有樣式... */
}

List 模式適配

若使用列表模式 (list.phtml 中 list 模式),需針對 .products-list 編寫對應 CSS,或統一類名。建議將標籤渲染邏輯封裝為 Helper 或 Block 方法,模板中調用 $this->getProductLabels($_product) 復用。

後台配置

  1. 編輯產品 → 常規 → 新品起始日期 / 新品結束日期
  2. 編輯產品 → 價格 → 特價 / 特價起始日期 / 特價結束日期
  3. 清除緩存:System > Cache Management > Flush Magento Cache

進階優化

  • 性能:避免在模板中重複 strtotime,可在 Block _beforeToHtml() 預計算
  • 多語言:標籤文字用 __('NEW') ?> 支持翻譯
  • 圖片標籤:CSS background-image 使用 SVG/Data URI 避免額外請求
  • 全站統一:創建 catalog/product/label.phtml 部分模板,list.phtml、view.phtml、new.phtml 共同 include

常見問題

  • 標籤不顯示:檢查日期是否保存成功(數據庫 catalog_product_entity_datetime)、時區設置、緩存是否清除
  • 位置錯誤:父容器缺少 position: relative,或 top/left 數值需微調
  • 折扣計算錯誤:確認 getSpecialPrice() 返回數值而非格式化字符串,必要時用 Mage::helper('core')->currency() 反解析
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved