在之前一篇在不同店铺获取产品网址的文章中,有人指出,如果当你想要获取的产品已经被重写那么将很麻烦。我想到一个返回被重写产品网址的方法。你将需要添加一个店铺的基本网址来返回一个完整网址的值。

要注意的是:这个方法只有在设置了网址关键字(URL key)属性集范围的店视图(store view)才有效。这意味着一件商品在不同店视图中的网址是不一样的。例如:一个产品在英文店铺中的网址关键字(URL key)是'nokia-blue',在德文店铺中的网址关键字(URL key)是'nokia blau'。这将作用于你正在编辑产品的重写。如果你决定在网址重写中添加一个你自己的网址重写,也许你有一个很好的理由,但是我们不会被这种情况覆盖。

这次我不会去创建和注册一个模块。让我们以加入这个方法到你的模块助手中开始。

app/code/community/Alwayly/Rewrites/Helper/Data.php

<?php
class Alwayly_Rewrites_Helper_Data extends Mage_Core_Helper_Abstract
{
    public function rewrittenProductUrl($productId, $categoryId, $storeId)
    {
        $coreUrl = Mage::getModel('core/url_rewrite');
        $idPath = sprintf('product/%d', $productId);
        if ($categoryId) {
            $idPath = sprintf('%s/%d', $idPath, $categoryId);
        }
        $coreUrl->setStoreId($storeId);
        $coreUrl->loadByIdPath($idPath);
 
        return $coreUrl->getRequestPath();
    }
}
?>

现在我们将做一个小的试演。如你所见,这个方法中接收productId, $categoryId 和 $storeId作为参数。要了解网址(URLS)在被重写前是什么样的,我们一起看下我们数据库中core_url_rewrite的这张表。

core_url_rewrite表

一个不在任何类别中产品的id_path表现形式为product/productId,如果它属于任意的类别,它将表现为product/productId/categoryId

让我们回到我们的方法。我们将用Magento注册表中的数据创建一个id_path的结构体。在我们寻找重写前我们需要为模型用setStoreId()设置店铺的Id。在这之后,我们将用loadByIdPath()读取我们重写了的地址列。现在剩下的就是获取一个请求通道,也就是产品网址中重写的部分。我们将用Magento中的core/url_rewrite模型来实现这些。

一个例子是,指向你正在寻找的同一产品的语言切换器,但在不同的店视图中。只需将下面的代码放入你的languages.phtml文件。app/design/base/default/template/page/html/switch/languages.phtml

<?php if(count($this->getStores())>1): ?>
    <?php
    $helper = Mage::helper('inchoo_rewrites');
    $prod = Mage::registry('current_product');
    $categ = Mage::registry('current_category');
    $categId = $categ ? $categ->getId() : null;
 
    ?>
    <div class="form-language">
        <label for="select-language"><?php echo $this->__('Your Language:') ?></label>
        <select id="select-language" title="<?php echo $this->__('Your Language') ?>" onchange="window.location.href=this.value">
            <?php foreach ($this->getStores() as $_lang): ?>
                <?php $_selected = ($_lang->getId() == $this->getCurrentStoreId()) ? ' selected="selected"' : '' ?>
                <option value="<?php
                    if($prod) {
                        echo $_lang->getBaseUrl() . $helper->rewrittenProductUrl($prod->getId(), $categId, $_lang->getId()) . '?___store=' . $_lang->getCode();
                    }else{
                        echo $_lang->getCurrentUrl(false);
                    }
                ?>"<?php echo $_selected ?>><?php echo $this->escapeHtml($_lang->getName()) ?></option>
            <?php endforeach; ?>
        </select>
    </div>
<?php endif; ?>

你的语言切换器源码应该有些像这样(只要你的产品至少在一个店铺中有不同的网址)

language switcher

希望这将对你们掌握多店铺中网址重写的概念有所帮助。

360magento提供专业的基于magento系统的电商网站开发服务,如有需求或相关咨询,请与我们联系