Добавление исключения из модификации слоистых навигационных названий страниц
-
16-10-2019 - |
Вопрос
Мы используем следующий код в app/code/local/Mage/Page/Block/Html/Head.php
Чтобы обнаружить, когда фильтр активен из слоистой навигации, а затем внести поправки в заголовок страницы и мета -описание на основе этого источника из Designend.
public $layerFilters;
public $currentFilters;
public function getLayersMeta(){
$this->layerFilters = '';
$state_block = $this->getLayout()->createBlock("catalog/layer_state");
$this->currentFilters = $state_block->getActiveFilters();
if(!empty($this->currentFilters)) {
foreach($this->currentFilters as $filter) {
$this->layerFilters .= ($this->layerFilters!='') ? ', '.$filter->getName() : $filter->getName();
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', $filter->getFilter()->getRequestVar());
foreach($attribute->getSource()->getAllOptions(true, true) as $option) {
if($filter->getValue() == $option['value']) {
$this->layerFilters .= ' - '.strtr($option['label'],array('"'=>"''"));
}
}
}
$this->layerFilters = ($this->layerFilters!='') ? $this->__('Shopping by: ').$this->layerFilters.' - ' : '';
}
Это работает хорошо и добавляет дополнительные данные к заголовку страницы для всех страниц с слоистыми навигационными фильтрами (параметры запроса) в URL.
Что мы хотели бы сделать, так это добавить исключение в getLayersMeta
функция, которая форматирует заголовок страницы по -разному, когда фильтр производитель.
Я не уверен, нужно ли мне добавить elseif
оператор, чтобы поймать параметр запроса «производитель», как if($this->getRequest()->getParam('manufacturer') {}
.
Распространение с ответом @mpaepper ...
/**
* Modifying the page titles for layered navigation (filters) pages.
*
*
*
*/
public $layerFilters;
public $currentFilters;
public $orderBy;
public $currentPage;
public function getLayersMeta(){
$manufacturer = Mage::app()->getRequest()->getParam('manufacturer');
if (!empty($manufacturer)) {
$this->_handleManufacturerMeta();
return false;
}
$this->layerFilters = '';
$state_block = $this->getLayout()->createBlock("catalog/layer_state");
$this->currentFilters = $state_block->getActiveFilters();
if(!empty($this->currentFilters)) {
foreach($this->currentFilters as $filter) {
$this->layerFilters .= ($this->layerFilters!='') ? ', '.$filter->getName() : $filter->getName();
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', $filter->getFilter()->getRequestVar());
foreach($attribute->getSource()->getAllOptions(true, true) as $option) {
if($filter->getValue() == $option['value']) {
$this->layerFilters .= ' - '.strtr($option['label'],array('"'=>"''"));
}
}
}
$this->layerFilters = ($this->layerFilters!='') ? $this->__('Shopping by: ').$this->layerFilters.' - ' : '';
}
$this->orderBy = '';
if($this->getRequest()->getParam('order') && $this->getRequest()->getParam('dir')) {
$this->orderBy .= $this->__('Sort by ').$this->__(htmlspecialchars($this->getRequest()->getParam('order')));
$this->orderBy .= (htmlspecialchars($this->getRequest()->getParam('dir')) == 'asc') ? ', '.$this->__('ascending') : ', '.$this->__('descending');
}
if($this->getRequest()->getParam('limit') && is_numeric($this->getRequest()->getParam('limit'))) {
$this->orderBy .= (($this->orderBy!='') ? ', ' : $this->__('show')).' '.$this->getRequest()->getParam('limit').' '.$this->__('per page');
}
if($this->getRequest()->getParam('p') && is_numeric($this->getRequest()->getParam('p'))) {
$this->currentPage = $this->__('Page').' '.$this->getRequest()->getParam('p').' - ';
}
$this->orderBy = ($this->orderBy!='') ? $this->orderBy.' - ' : '';
return $this->layerFilters.$this->orderBy.$this->currentPage;
}
protected function _handleManufacturerMeta() {
// Add manufacturer metas
}
Решение
Да, это был бы один вариант:
public function getLayersMeta() {
$manufacturer = Mage::app()->getRequest()->getParam('manufacturer');
if (!empty($manufacturer)) {
return $this->_handleManufacturerMeta();
}
// Your other logic which handles everything but manufacturer
}
protected function _handleManufacturerMeta() {
$manufacturer = $this->getRequest()->getParam('manufacturer');
$manufacturerValue = '';
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'manufacturer');
foreach($attribute->getSource()->getAllOptions(true, true) as $option) {
if($manufacturer == $option['value']) {
$manufacturerValue = $option['label'];
}
}
return $this->__('My manufacturer is: ').$manufacturerValue;
}
РЕДАКТИРОВАТЬ: Я обновил свой пример и добавил пример кода. Метод _handlemanufacturermeta понадобится ваш пользовательский код, чтобы показать нужный текст для производителей. Логика заключается в том, что когда метод getLayersMeta () обнаруживает производителя, он возвращает текст из _handlemanufacturerersMeta. Если нет, он возвращает ваш текст, который у вас был до сих пор.
Имейте в виду, однако, что то, как описывает запись блока, это не очень хороший стиль (перезапись основной класс в локальном кодовом пространстве) - было бы лучше использовать переписывание или даже лучше некоторых наблюдателей.