This commit is contained in:
2026-09-15 10:35:56 +08:00
commit 782f8ea7aa
4086 changed files with 631288 additions and 0 deletions
@@ -0,0 +1,91 @@
<?php
namespace WeltPixel\LayeredNavigation\Block\Adminhtml\Product\Attribute\Edit\Tab;
use Magento\Backend\Block\Template\Context;
use Magento\Backend\Block\Widget\Form\Generic;
use Magento\Catalog\Model\Entity\Attribute;
use Magento\Framework\Data\FormFactory;
use Magento\Framework\Registry;
/**
* @api
* @since 100.0.2
*/
class Options extends Generic implements \Magento\Backend\Block\Widget\Tab\TabInterface
{
/**
* @param Context $context
* @param Registry $registry
* @param FormFactory $formFactory
* @param array $data
*/
public function __construct(
Context $context,
Registry $registry,
FormFactory $formFactory,
array $data = []
) {
parent::__construct($context, $registry, $formFactory, $data);
}
/**
* Return Tab label
*
* @return string
* @api
*/
public function getTabLabel() {
return __('WeltPixel Layered Navigation Properties');
}
/**
* Return Tab title
*
* @return string
* @api
*/
public function getTabTitle() {
return __('WeltPixel Layered Navigation Properties');
}
/**
* Can show tab in tabs
*
* @return boolean
* @api
*/
public function canShowTab() {
return true;
}
/**
* Tab is hidden
*
* @return boolean
* @api
*/
public function isHidden() {
return false;
}
/**
* {@inheritdoc}
* @return $this
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
protected function _prepareForm()
{
/** @var Attribute $attributeObject */
$attributeObject = $this->_coreRegistry->registry('entity_attribute');
/** @var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create(
['data' => ['id' => 'edit_form', 'action' => $this->getData('action'), 'method' => 'post']]
);
$this->_eventManager->dispatch('product_attribute_form_build_weltpixel_layerednavigation_tab', ['form' => $form]);
$this->setForm($form);
$form->setValues($attributeObject->getData());
return parent::_prepareForm();
}
}
@@ -0,0 +1,30 @@
<?php
namespace WeltPixel\LayeredNavigation\Block\Adminhtml\System\Config;
/**
* Implement
* @category WeltPixel_OwlCarouselSlider
* @package WeltPixel_OwlCarouselSlider
* @module OwlCarouselSlider
* @author WeltPixel_OwlCarouselSlider Developer
*/
class InfoMessage extends \Magento\Config\Block\System\Config\Form\Field
{
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$number = (int)substr($element->getId(), -1);
$html = '
<div class="message" style="text-align: center; margin-top: 20px;">
<p>' . __('For more settings on attribute level, go to
<strong>Stores -> Attributes -> Product -> [select desired attribute from grid] ->
Storefront Properties -> WeltPixel Layered Navigation Properties</strong>
section.') . '</p>
</div>
';
return $html;
}
}
@@ -0,0 +1,85 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Block\LayeredNavigation;
use Magento\Eav\Model\Entity\Attribute;
use Magento\Catalog\Model\ResourceModel\Layer\Filter\AttributeFactory;
use Magento\Framework\View\Element\Template;
/**
* Class RenderLayered
* @package WeltPixel\LayeredNavigation\Block\LayeredNavigation
*/
class RenderLayered extends \Magento\Swatches\Block\LayeredNavigation\RenderLayered
{
/**
* Path to template file.
*
* @var string
*/
protected $_template = 'WeltPixel_LayeredNavigation::product/layered/renderer.phtml';
/**
* @var \WeltPixel\LayeredNavigation\Model\AttributeOptions
*/
protected $_attributeOptions;
/**
* RenderLayered constructor.
* @param Template\Context $context
* @param Attribute $eavAttribute
* @param AttributeFactory $layerAttribute
* @param \Magento\Swatches\Helper\Data $swatchHelper
* @param \Magento\Swatches\Helper\Media $mediaHelper
* @param \WeltPixel\LayeredNavigation\Model\AttributeOptions $attributeOptions
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
Attribute $eavAttribute,
AttributeFactory $layerAttribute,
\Magento\Swatches\Helper\Data $swatchHelper,
\Magento\Swatches\Helper\Media $mediaHelper,
\WeltPixel\LayeredNavigation\Model\AttributeOptions $attributeOptions,
array $data = []
) {
$this->eavAttribute = $eavAttribute;
$this->layerAttribute = $layerAttribute;
$this->swatchHelper = $swatchHelper;
$this->mediaHelper = $mediaHelper;
$this->_attributeOptions = $attributeOptions;
parent::__construct($context,$eavAttribute,$layerAttribute,$swatchHelper,$mediaHelper, $data);
}
/**
* return the 'Is Multiselect' attribute configuration value
*
* @return mixed
*/
public function getIsMultiSelect($attrId)
{
return ($attrId > 0) ? $this->getWpAttributeOptions($attrId)->getIsMultiselect() : 0;
}
/**
* Return wp attribute options
*
* @param $attributeId
* @return mixed
*/
public function getWpAttributeOptions($attrId)
{
$this->_attributeOptionsObj = ($attrId > 0) ? $this->_attributeOptions->getDisplayOptionsByAttribute($attrId) : '';
return $this->_attributeOptionsObj;
}
}
@@ -0,0 +1,56 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Block;
use Magento\Framework\View\Element\Template\Context;
use WeltPixel\LayeredNavigation\Helper\Data;
class LayeredNavigationAdd extends \Magento\Framework\View\Element\Template
{
/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
protected $_scopeConfig;
/**
* @var Data
*/
protected $_wpHelper;
/**
* AjaxInfiniteScroll constructor.
* @param Context $context
* @param Data $helper
* @param array $data
*/
public function __construct(
Context $context,
Data $helper,
array $data = []
) {
$this->_scopeConfig = $context->getScopeConfig();
$this->_wpHelper = $helper;
parent::__construct($context, $data);
}
/**
* check if module enabled and ajax mode is enabled
*
* @return bool
*/
public function isLnEnabled() {
$is = false;
if($this->_wpHelper->isEnabled()) {
$is = ($this->_wpHelper->isAjaxEnabled()) ? true : false;
}
return $is;
}
}
+387
View File
@@ -0,0 +1,387 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Block;
use Magento\Catalog\Model\Product\ProductList\Toolbar as ToolbarModel;
use Magento\Catalog\Helper\Product\ProductList;
/**
* Class Navigation
* @package WeltPixel\LayeredNavigation\Block
*/
class Navigation extends \Magento\LayeredNavigation\Block\Navigation
{
/**
* Catalog layer
*
* @var \Magento\Catalog\Model\Layer
*/
protected $_catalogLayer;
/**
* @var \Magento\Catalog\Model\Layer\FilterList
*/
protected $filterList;
/**
* @var \Magento\Catalog\Model\Layer\AvailabilityFlagInterface
*/
protected $visibilityFlag;
/**
* @var ProductList
*/
protected $_productListHelper;
/**
* Default Order field
*
* @var string
*/
protected $_orderField = null;
/**
* Default direction
*
* @var string
*/
protected $_direction = ProductList::DEFAULT_SORT_DIRECTION;
/**
* @var \WeltPixel\LayeredNavigation\Helper\Data
*/
protected $_wpHelper;
/**
* @var \Magento\Framework\Registry
*/
protected $_registry;
/**
* @var \WeltPixel\LayeredNavigation\Model\AttributeOptions
*/
protected $_attributeOptions;
/**
* @var \Magento\Swatches\Helper\Data
*/
private $swatchHelper;
/**
* Navigation constructor.
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Catalog\Model\Layer\Resolver $layerResolver
* @param \Magento\Catalog\Model\Layer\FilterList $filterList
* @param \Magento\Catalog\Model\Layer\AvailabilityFlagInterface $visibilityFlag
* @param ProductList $productListHelper
* @param \WeltPixel\LayeredNavigation\Helper\Data $wpHelper
* @param \WeltPixel\LayeredNavigation\Model\AttributeOptions $attributeOptions
* @param \Magento\Framework\Registry $registry
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\Layer\Resolver $layerResolver,
\Magento\Catalog\Model\Layer\FilterList $filterList,
\Magento\Catalog\Model\Layer\AvailabilityFlagInterface $visibilityFlag,
ProductList $productListHelper,
\WeltPixel\LayeredNavigation\Helper\Data $wpHelper,
\WeltPixel\LayeredNavigation\Model\AttributeOptions $attributeOptions,
\Magento\Framework\Registry $registry,
\Magento\Swatches\Helper\Data $swatchHelper,
array $data = []
)
{
$this->_catalogLayer = $layerResolver->get();
$this->filterList = $filterList;
$this->visibilityFlag = $visibilityFlag;
$this->_productListHelper = $productListHelper;
$this->_wpHelper = $wpHelper;
$this->_attributeOptions = $attributeOptions;
$this->_registry = $registry;
$this->swatchHelper = $swatchHelper;
parent::__construct($context, $layerResolver, $filterList, $visibilityFlag, $data);
}
/**
* @return mixed
*/
public function isCategoryFilterVisible()
{
return $this->_wpHelper->showCategoriesBlock();
}
/**
* @return mixed
*/
public function isAjaxMode()
{
return $this->_wpHelper->isAjaxEnabled();
}
/**
* @return mixed
*/
public function isAjaxScrollToTop()
{
return $this->_wpHelper->isAjaxScrollToTopEnabled();
}
/**
* @return mixed
*/
public function isAutoClose()
{
return $this->_wpHelper->isAutoClose();
}
/**
* @return mixed
*/
public function noOfColumns() {
return $this->_wpHelper->getNoColumns();
}
/**
* @return mixed
*/
public function boxHeight() {
return $this->_wpHelper->getSlideDownHeight();
}
/**
* @return mixed
*/
public function filterColumnHeight() {
return $this->_wpHelper->getFilterColumnHeight();
}
/**
* check if current filter is a category filter
*
* @param $filter
* @return bool
*/
public function isCategoryFilter($filter)
{
return ($filter->getRequestVar() == $this->_wpHelper->getCategoryParamLabel()) ? true : false;
}
/**
* check if current filter is a rating filter
*
* @param $filter
* @return bool
*/
public function isRatingFilter($filter)
{
return ($filter->getRequestVar() == $this->_wpHelper->getRatingParamLabel()) ? true : false;
}
/**
* @return \Magento\Framework\Phrase|string
*/
public function getFilterButtonHtml()
{
return $this->_wpHelper->getFilterButtonStyle();
}
/**
* Return wp attribute options
*
* @param $attributeId
* @return mixed
*/
public function getWpAttributeOptions($attributeId)
{
return $this->_attributeOptions->getDisplayOptionsByAttribute($attributeId);
}
/**
* check if module enabled and ajax mode is enabled
*
* @return bool
*/
public function isLnEnabled() {
$is = false;
if($this->_wpHelper->isEnabled()) {
$is = ($this->_wpHelper->isAjaxEnabled()) ? true : false;
}
return $is;
}
/**
* set filter tab status
*
* @return string
*/
public function getActiveFilters() {
$stateFilters = $this->_catalogLayer->getState()->getFilters();
$stateFilterIds = [];
foreach ($stateFilters as $_filter) {
if (in_array($_filter->getFilter()->getRequestVar(), [$this->_wpHelper->getCategoryParamLabel(), $this->_wpHelper->getRatingParamLabel()])) {
continue;
}
$dataAttrId = $_filter->getFilter()->getAttributeModel()->getAttributeId();
$stateFilterIds[] = $dataAttrId;
}
$filters = $this->getFilters();
$activeFilters = [];
$ctr = 0;
$isSlideDownMode = ($this->_wpHelper->getSidebarStyle() == 2 ) ? true : false;
foreach($filters as $k => $filter) {
if($filter->getRequestVar() == $this->_wpHelper->getCategoryParamLabel() && !$isSlideDownMode) {
if(($filter->getItemsCount() > 0) && $this->_wpHelper->showCategoryFilterAs()) {
$activeFilters[] = $ctr; $ctr++;
}
continue;
} else {
if($filter->getItemsCount() > 0) {
if($isSlideDownMode) {
$activeFilters[] = $ctr;
$ctr++;
continue;
}
if($filter->getRequestVar() == $this->_wpHelper->getRatingParamLabel()) {
if($this->_wpHelper->getRatingFilterDisplay() == '1') $activeFilters[] = $ctr;
if($filter->getItemsCount()) $ctr++;
continue;
}
$attributeId = $filter->getAttributeModel()->getAttributeId();
$categoryVisibility = $this->getCategoryVisibility($attributeId);
if(!$categoryVisibility) {
continue;
}
if($attributeId) {
$wpOptions = $this->getWpAttributeOptions($attributeId);
if($wpOptions->getData()) {
if($wpOptions->getDisplayOption() == '1' || $wpOptions->getDisplayOption() == '2') {
$activeFilters[] = $ctr;
}
}
if ($this->swatchHelper->isSwatchAttribute($filter->getAttributeModel())) {
if($wpOptions->getDisplayOption() == '1') {
$activeFilters[] = $ctr;
}
}
if (in_array($attributeId, $stateFilterIds) && $wpOptions->getKeepOpenAfterFilter()) {
$activeFilters[] = $ctr;
}
}
$ctr++;
}
}
}
$activeFilters = array_unique($activeFilters);
$activeFiltersStr = implode(' ', $activeFilters);
return $activeFiltersStr;
}
/**
* Return current URL with rewrites and additional parameters
*
* @param array $params Query parameters
* @return string
*/
public function getPagerUrl($params = [])
{
$urlParams = [];
$urlParams['_current'] = true;
$urlParams['_escape'] = false;
$urlParams['_use_rewrite'] = true;
$urlParams['_query'] = $params;
return $this->getUrl('*/*/*', $urlParams);
}
/**
* Retrieve widget options in json format
*
* @param array $customOptions Optional parameter for passing custom selectors from template
* @return string
*/
public function getWidgetOptionsJson(array $customOptions = [])
{
$defaultMode = $this->_productListHelper->getDefaultViewMode($this->getModes());
$options = [
'mode' => ToolbarModel::MODE_PARAM_NAME,
'direction' => ToolbarModel::DIRECTION_PARAM_NAME,
'order' => ToolbarModel::ORDER_PARAM_NAME,
'limit' => ToolbarModel::LIMIT_PARAM_NAME,
'modeDefault' => $defaultMode,
'directionDefault' => $this->_direction ?: ProductList::DEFAULT_SORT_DIRECTION,
'orderDefault' => $this->getOrderField(),
'limitDefault' => $this->_productListHelper->getDefaultLimitPerPageValue($defaultMode),
'url' => $this->getPagerUrl(),
];
$options = array_replace_recursive($options, $customOptions);
return json_encode(['productListToolbarForm' => $options]);
}
/**
* Get order field
*
* @return null|string
*/
protected function getOrderField()
{
if ($this->_orderField === null) {
$this->_orderField = $this->_productListHelper->getDefaultSortField();
}
return $this->_orderField;
}
/**
* @return bool
*/
public function getCategoryVisibility($attributeId = false)
{
if(!$attributeId) {
return true;
}
$visibility = true;
$category = $this->_registry->registry('current_category');
if ($attributeId > 0 && $category) {
$currentCatId = $category->getId();
$categoryVisibility = $this->getWpAttributeOptions($attributeId)->getCategoryVisibility();
$categoriesIds = $this->getWpAttributeOptions($attributeId)->getCategoryIds() ?? '';
$categoriesArr = explode(',', $categoriesIds);
if ($categoryVisibility == 1) {
if (in_array($currentCatId, $categoriesArr)) {
$visibility = true;
} else {
$visibility = false;
}
}
if ($categoryVisibility == 2) {
if (in_array($currentCatId, $categoriesArr)) {
$visibility = false;
} else {
$visibility = true;
}
}
}
return $visibility;
}
}
@@ -0,0 +1,370 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Block\Navigation;
use Magento\Framework\App\ProductMetadataInterface;
use Magento\Framework\View\Element\Template;
use Magento\Catalog\Model\Layer\Filter\FilterInterface;
/**
* Class FilterRenderer
* @package WeltPixel\LayeredNavigation\Block\Navigation
*/
class FilterRenderer extends \Magento\LayeredNavigation\Block\Navigation\FilterRenderer
{
/**
* @var \WeltPixel\LayeredNavigation\Helper\Data
*/
protected $_wpHelper;
/**
* @var \WeltPixel\LayeredNavigation\Model\AttributeOptions
*/
protected $_attributeOptions;
/**
* @var
*/
protected $_attributeId;
/**
* @var
*/
protected $_attributeOptionsObj;
/**
* @var int
*/
protected $maxPrice;
/**
* @var int
*/
protected $minPrice;
/**
* @var int
*/
protected $maxPriceX;
/**
* @var int
*/
protected $minPriceX;
/**
* @var \Magento\Framework\Registry
*/
protected $_registry;
/**
* @var \Magento\Framework\Pricing\PriceCurrencyInterface
*/
protected $_currency;
/**
* @var \Magento\Theme\Block\Html\Pager
*/
private $htmlPagerBlock;
/**
* @var ProductMetadataInterface
*/
protected $productMetadata;
/**
* FilterRenderer constructor.
* @param ProductMetadataInterface $productMetadata
* @param \WeltPixel\LayeredNavigation\Helper\Data $wpHelper
* @param \WeltPixel\LayeredNavigation\Model\AttributeOptions $attributeOptions
* @param \Magento\Framework\Registry $registry
* @param \Magento\Framework\Pricing\PriceCurrencyInterface $currency
* @param \Magento\Theme\Block\Html\Pager $htmlPagerBlock
* @param Template\Context $context
* @param array $data
*/
public function __construct(
ProductMetadataInterface $productMetadata,
\WeltPixel\LayeredNavigation\Helper\Data $wpHelper,
\WeltPixel\LayeredNavigation\Model\AttributeOptions $attributeOptions,
\Magento\Framework\Registry $registry,
\Magento\Framework\Pricing\PriceCurrencyInterface $currency,
\Magento\Theme\Block\Html\Pager $htmlPagerBlock,
Template\Context $context,
array $data = []
)
{
$this->productMetadata = $productMetadata;
$this->_wpHelper = $wpHelper;
$this->_attributeOptions = $attributeOptions;
$this->_registry = $registry;
$this->_currency = $currency;
$this->htmlPagerBlock = $htmlPagerBlock;
parent::__construct($context, $data);
}
/**
* @param FilterInterface $filter
* @return string
*/
public function render(FilterInterface $filter)
{
$this->filter = $filter;
if ($this->_wpHelper->isEnabled()) {
if ($filter->getRequestVar() == 'price' && $this->_wpHelper->getPriceIsSliderMode()) {
$collection = $this->filter->getLayer()->getProductCollection();
$currentCatId = ($this->_registry->registry('current_category')) ? $this->_registry->registry('current_category')->getId() : "";
$basePriceData = $this->_registry->registry('price_filter');
if (is_array($basePriceData) && $currentCatId && array_key_exists($currentCatId, $basePriceData)) {
$this->minPriceX = $basePriceData[$currentCatId]['min'];
$this->maxPriceX = $basePriceData[$currentCatId]['max'];
} else {
$this->minPriceX = ($this->minPriceX == null) ? $collection->getMinPrice() : $this->minPriceX;
$this->maxPriceX = ($this->maxPriceX == null) ? $collection->getMaxPrice() : $this->maxPriceX;
}
$this->minPrice = ($this->minPrice == null) ? $collection->getMinPrice() : $this->minPrice;
$this->maxPrice = ($this->maxPrice == null) ? $collection->getMaxPrice() : $this->maxPrice;
$this->setTemplate('layer/slider.phtml');
} else {
$this->setTemplate('layer/filter.phtml');
}
}
$html = parent::render($filter);
return $html;
}
/**
* @return array
*/
public function getPriceConfigData()
{
$range = [
'minX' => floor($this->minPriceX),
'maxX' => ceil($this->maxPriceX),
'min' => floor($this->minPrice),
'max' => ceil($this->maxPrice),
'step' => 1,
'currency' => $this->_currency->getCurrencySymbol()
];
return $range;
}
/**
* @return bool
*/
public function priceIsInputType()
{
return $this->_wpHelper->canShowPriceInput();
}
/**
* @return string
*/
public function getSliderApplyUrl()
{
$params = [
'price' => $this->minPrice . '-' . $this->maxPrice,
$this->htmlPagerBlock->getPageVarName() => null
];
$urlParams = [];
$urlParams['_current'] = true;
$urlParams['_escape'] = false;
$urlParams['_use_rewrite'] = true;
$urlParams['_query'] = $params;
return $this->getUrl('*/*/*', $urlParams);
}
/**
* @return mixed
*/
public function getPriceStep()
{
$step = $this->_wpHelper->getPriceRangeStep();
return ($step > $this->maxPrice) ? $this->maxPrice : $step;
}
/**
* @param $filter
*/
public function setAttributeId($filter)
{
if ($filter->getRequestVar() == $this->_wpHelper->getCategoryParamLabel()) {
$this->_attributeId = $this->_wpHelper->getCategoryParamLabel();
} elseif ($filter->getRequestVar() == $this->_wpHelper->getRatingParamLabel()) {
$this->_attributeId = $this->_wpHelper->getRatingParamLabel();
} else {
$this->_attributeId = $filter->getAttributeModel()->getAttributeId();
}
}
/**
* Return wp attribute options
*
* @param $attributeId
* @return mixed
*/
public function getWpAttributeOptions()
{
$this->_attributeOptionsObj = ($this->_attributeId > 0) ? $this->_attributeOptions->getDisplayOptionsByAttribute($this->_attributeId) : '';
return $this->_attributeOptionsObj;
}
/**
* @return mixed
*/
public function getAttributeId()
{
return $this->_attributeId;
}
/**
* return the 'Visible Options' attribute configuration value
*
* @return mixed
*/
public function getVisibleItems()
{
if ($this->_attributeId > 0) {
$attributeOptions = $this->getWpAttributeOptions();
if ($attributeOptions) {
return $attributeOptions->getVisibleOptions();
} else {
return '';
}
}
return '';
}
/**
* return the 'Visible Options Step' attribute configuration value
*
* @return mixed
*/
public function getVisibleItemsStep()
{
if ($this->_attributeId > 0) {
$attributeOptions = $this->getWpAttributeOptions();
if ($attributeOptions) {
return $attributeOptions->getVisibleOptionsStep();
} else {
return '';
}
}
return '';
}
/**
* return the 'Show Qty' attribute configuration value
*
* @return mixed
*/
public function getShowQty()
{
if ($this->_attributeId == $this->_wpHelper->getRatingParamLabel()) {
return $this->_wpHelper->getRatingFilterCounter();
} elseif ($this->_attributeId == $this->_wpHelper->getCategoryParamLabel()) {
return '';
} else {
$attributeOptions = $this->getWpAttributeOptions();
if ($attributeOptions) {
return $attributeOptions->getShowQuantity();
}
return '';
}
}
/**
* return the 'Is Multiselect' attribute configuration value
*
* @return mixed
*/
public function getIsMultiSelect()
{
if ($this->_attributeId == $this->_wpHelper->getRatingParamLabel()) {
return $this->_wpHelper->isRatingFilterMultiselect();
} elseif ($this->_attributeId == $this->_wpHelper->getCategoryParamLabel()) {
return '';
} else {
$attributeOptions = $this->getWpAttributeOptions();
if ($attributeOptions) {
return $attributeOptions->getIsMultiselect();
}
return '';
}
}
/**
* return the 'Instant Search' attribute configuration value
*
* @return string
*/
public function canShowInstantSearch()
{
if ($this->_attributeId > 0) {
$attributeOptions = $this->getWpAttributeOptions();
if ($attributeOptions) {
return $attributeOptions->getInstantSearch();
}
return '';
}
return '';
}
/**
* return the 'Instant Search Mobile' attribute configuration value
*
* @return string
*/
public function canShowInstantSearchMobile()
{
if ($this->_attributeId > 0) {
$attributeOptions = $this->getWpAttributeOptions();
if ($attributeOptions) {
return $attributeOptions->getInstantSearchMobile();
}
return '';
}
return '';
}
/**
* @return string
*/
public function getCategoryParamLabel()
{
return $this->_wpHelper->getCategoryParamLabel();
}
/**
* @return string
*/
public function getRatingParamLabel()
{
return $this->_wpHelper->getRatingParamLabel();
}
/**
* @return string
*/
public function getSliderJsWidget()
{
$jsSliderWidget = 'jquery/ui-modules/widgets/slider';
$magentoVersion = $this->productMetadata->getVersion();
if (version_compare($magentoVersion, '2.4.4', '<')) {
$jsSliderWidget = 'jquery-ui-modules/slider';
}
return $jsSliderWidget;
}
}
@@ -0,0 +1,99 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Block\Navigation;
/**
* Layered navigation state
*
* @api
* @since 100.0.2
*/
class State extends \Magento\LayeredNavigation\Block\Navigation\State
{
/**
* @var array
*/
protected $ratesStep = [
'0-20' => 1,
'21-40' => 2,
'41-60' => 3,
'61-80' => 4,
'81-100' => 5,
];
/**
* Catalog layer
*
* @var \Magento\Catalog\Model\Layer
*/
protected $_catalogLayer;
/**
* @var \WeltPixel\LayeredNavigation\Helper\Data
*/
protected $_wpHelper;
/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Catalog\Model\Layer\Resolver $layerResolver
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\Layer\Resolver $layerResolver,
\WeltPixel\LayeredNavigation\Helper\Data $wpHelper,
array $data = []
) {
$this->_catalogLayer = $layerResolver->get();
$this->_wpHelper = $wpHelper;
parent::__construct($context,$layerResolver, $data);
if($this->_wpHelper->isEnabled()) {
$this->_template = 'WeltPixel_LayeredNavigation::layer/state.phtml';
}
}
/**
* @param $filter
* @return string
*/
public function getRateFilterLabel($filter) {
$selectedValue = $filter->getValue();
$countStars = 1;
if(is_array($selectedValue)) {
$val = $selectedValue[0].'-'.$selectedValue[1];
$countStars = $this->ratesStep[$val];
} else {
$valArr = explode('-', $selectedValue);
$val = $valArr[0].'-'.$valArr[1];
$countStars = $this->ratesStep[$val];
}
$label = '<div class="rating-summary" style="display: inline-block;margin-top: -5px;">
<div class="rating-result" title="up to '.$countStars*20 .'%"">
<span style="width:'.$countStars*20 .'%"></span>
</div>
</div>';
return $label;
}
/**
* @return string
*/
public function getCategoryParamLabel() {
return $this->_wpHelper->getCategoryParamLabel();
}
/**
* @return string
*/
public function getRatingParamLabel() {
return $this->_wpHelper->getRatingParamLabel();
}
}
@@ -0,0 +1,4 @@
Important notes:
- Extension files for Magento versions 2.4 or higher.
- Files NOT compatible with Magento version 2.0 - 2.3.x.
- Using different set of files for each Magento version for best performance.
+589
View File
@@ -0,0 +1,589 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Helper;
use Magento\Store\Model\ScopeInterface;
use \Magento\CatalogSearch\Model\ResourceModel\EngineInterface;
/**
* Class Data
* @package WeltPixel\LayeredNavigation\Helper
*/
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
const SLIDE_IN_STYLE = 1;
const SLIDE_DOWN_STYLE = 2;
const FILTER_BUTTON_LABEL = 'Filter';
const PRICE_FILTER_SLIDER = 2;
const PRICE_FILTER_INPUT = 1;
const CATEGORY_PARAM_LABEL = 'cat';
const RATING_PARAM_LABEL = 'rat';
protected $_currentEngine = '';
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $_storeManager;
/**
* @var int
*/
protected $_storeId;
/**
* @var Config
*/
private $pageConfig;
/**
* Data constructor.
* @param \Magento\Framework\App\Helper\Context $context
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Framework\View\Page\Config $pageConfig
*/
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\View\Page\Config $pageConfig
)
{
$this->_storeManager = $storeManager;
$this->pageConfig = $pageConfig;
parent::__construct($context);
$this->_storeId = $this->getCurrentStoreId();
}
/**
* @return string
*/
public function getRatingParamLabel() {
return self::RATING_PARAM_LABEL;
}
/**
* @return string
*/
public function getCategoryParamLabel() {
return self::CATEGORY_PARAM_LABEL;
}
/**
* Return current store_id
*
* @return int
*/
public function getCurrentStoreId()
{
return $this->_storeManager->getStore()->getId();
}
/**
* @param int $storeId
* @return mixed
*/
public function isEnabled($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/general/enable', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param int $storeId
* @return mixed
*/
public function isAjaxEnabled($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/general/ajax', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param int $storeId
* @return mixed
*/
public function isAjaxScrollToTopEnabled($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/general/ajax_scroll_top', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param int $storeId
* @return mixed
*/
public function getSidebarStyle($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/sb_style', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param int $storeId
* @return mixed
*/
public function getNoColumns($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/slide_down_columns', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param int $storeId
* @return mixed
*/
public function getSlideDownHeight($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/slide_down_height', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param int $storeId
* @return mixed
*/
public function getFilterColumnHeight($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/filter_column_height', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param int $storeId
* @return mixed
*/
public function showCategoriesBlock($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/category_block', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param int $storeId
* @return mixed
*/
public function showCategoryFilterAs($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/show_category_filter_as', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param int $storeId
* @return mixed
*/
public function showCompareBlock($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/compare_block', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param int $storeId
* @return mixed
*/
public function showWishlistBlock($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/wishlist_block', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param int $storeId
* @return mixed
*/
public function showRecentlyOrderedBlock($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/recentlyordered_block', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return mixed
*/
public function getFilterButton($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/filter_button', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return mixed
*/
public function showInstantSearch($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/instant_search', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return mixed
*/
public function showInstantSearchMobile($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/instant_search_mobile', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* Filter Button option
* 0-icon only
* 1-icon & label
* 2-label only
*
* @return \Magento\Framework\Phrase|string
*/
public function getFilterButtonStyle()
{
$slideDownModeAppend = ($this->getSidebarStyle() == self::SLIDE_DOWN_STYLE) ? "<span class='wp-slide-down-add'></span>" : '';
switch ($this->getFilterButton()) {
case 0:
$filterButtonHtml = "<b class='wp-slide-in'></b>" . $slideDownModeAppend;
break;
case 1:
$filterButtonHtml = "<b class='wp-slide-in'></b><b class='wp-filters-text'>" . /* @escapeNotVerified */ __(self::FILTER_BUTTON_LABEL) . "</b>" . $slideDownModeAppend;
break;
case 2:
$filterButtonHtml = __(self::FILTER_BUTTON_LABEL);
break;
default:
$filterButtonHtml = '';
}
return $filterButtonHtml;
}
/**
* @return bool
*/
public function getSlideMode() {
if($this->getSidebarStyle() == self::SLIDE_IN_STYLE) {
return 'slider-layer';
} else if($this->getSidebarStyle() == self::SLIDE_DOWN_STYLE) {
return 'slider-down-layer';
}
return false;
}
/**
* update class on body tag based on configuration settings
* the class is used for layered navigation view mode setting
*/
public function updateSliderBodyClass() {
if($this->getSlideMode()) {
$this->pageConfig->addBodyClass($this->getSlideMode());
} else {
$this->pageConfig->addBodyClass('default-layer');
}
}
/**
* Check the engine provider is 'elasticsearch'
* @deprecated
*
* @return bool
*/
public function isElasticSearchEngine() {
if(!$this->_currentEngine) {
$this->_currentEngine = $this->scopeConfig->getValue(EngineInterface::CONFIG_ENGINE_PATH, ScopeInterface::SCOPE_STORE);
}
if($this->_currentEngine == 'elasticsearch' || $this->_currentEngine == 'elasticsearch5' || $this->_currentEngine == 'elasticsearch6'
|| $this->_currentEngine == 'elasticsearch7' || $this->_currentEngine == 'elasticsearch8') {
return true;
}
return false;
}
/**
* Check the engine provider is 'elasticsearch' or 'opensearch'
*
* @return bool
*/
public function isElasticOrOpenSearchEngine() {
if(!$this->_currentEngine) {
$this->_currentEngine = $this->scopeConfig->getValue(EngineInterface::CONFIG_ENGINE_PATH, ScopeInterface::SCOPE_STORE);
}
if($this->_currentEngine == 'elasticsearch' || $this->_currentEngine == 'elasticsearch5' || $this->_currentEngine == 'elasticsearch6'
|| $this->_currentEngine == 'elasticsearch7' || $this->_currentEngine == 'opensearch') {
return true;
}
return false;
}
/**
* @return mixed
*/
public function getPriceRangeStep() {
return $this->scopeConfig->getValue('catalog/layered_navigation/price_range_step', ScopeInterface::SCOPE_STORE);
}
/**
* @param null $storeId
* @return mixed
*/
public function getPriceFilterStyle($storeId = null) {
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/price_filter', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @return bool
*/
public function getPriceIsSliderMode() {
$sliderMode = false;
if($this->getPriceFilterStyle() == self::PRICE_FILTER_SLIDER) {
$sliderMode = true;
}
return $sliderMode;
}
/**
* @param null $storeId
* @return mixed
*/
public function getPriceFilterInput($storeId = null) {
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/price_filter_input', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @return bool
*/
public function canShowPriceInput() {
$isInput = false;
$isInputSet = ($this->getPriceFilterInput() == self::PRICE_FILTER_INPUT) ? true : false;
if($this->getPriceIsSliderMode() && $isInputSet) {
$isInput = true;
}
return $isInput;
}
/**
* @param null $storeId
* @return mixed
*/
public function isRatingFilterEnabled($storeId = null) {
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/rating_filter', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @return bool|mixed
*/
public function getRatingFilterName($storeId = null) {
$name = false;
if($this->isRatingFilterEnabled() && $this->isEnabled()) {
$name = $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/rating_filter_name', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
return $name;
}
/**
* @param null $storeId
* @return mixed
*/
public function getRatingFilterPosition($storeId = null) {
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/rating_filter_position', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return mixed
*/
public function isRatingFilterMultiselect($storeId = null) {
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/rating_filter_multiselect', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return mixed
*/
public function getRatingFilterDisplay($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/rating_filter_display', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return mixed
*/
public function getRatingFilterCounter($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/rating_filter_counter', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return mixed
*/
public function isAutoClose($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/auto_close_sidebar', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return bool
*/
public function isShowHideDesktopFilterEnabled($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/allow_layered_show_hide', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return string
*/
public function getShowHideDesktopFilterState($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/layered_show_hide_state', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return string
*/
public function getHorizontalSidebarDesignVersion($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/horizontal_sb_design_version', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return string
*/
public function getHorizontalSidebarFilterPosition($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/horizontal_sb_design_v2_filter_position', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return string
*/
public function isHorizontalSidebarStickyEnabled($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/horizontal_sb_sticky_enable', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return string
*/
public function getSelectedFiltersOptions($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/sb_selected_filters_options', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return boolean
*/
public function displayMultiselectAttributeSelectedOptions($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/display_multiselect_selected_options', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return int
*/
public function getMobileThreshold($storeId = null)
{
$mobileThreshold = (int) $this->scopeConfig->getValue(
'weltpixel_frontend_options/breakpoints/screen__m',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
$storeId
);
return ($mobileThreshold) ? $mobileThreshold : 768;
}
/**
* @param null $storeId
* @return string
*/
public function getHorizontalV3FiltersButtonColor($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/horizontal_v3_filters_button_color', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return string
*/
public function getHorizontalV3FiltersTextColor($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/horizontal_v3_filters_text_color', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return string
*/
public function getHorizontalV3FiltersButtonHoverColor($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/horizontal_v3_filters_button_hover_color', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return string
*/
public function getHorizontalV3FiltersTextHoverColor($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/horizontal_v3_filters_text_hover_color', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return string
*/
public function getHorizontalFiltersBorder($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/horizontal_v3_border', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return string
*/
public function getHorizontalFiltersBorderRadius($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/horizontal_v3_border_radius', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return string
*/
public function getHorizontalFiltersBorderColor($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/horizontal_v3_border_color', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
/**
* @param null $storeId
* @return string
*/
public function getHorizontalBoxShadow($storeId = null)
{
return $this->scopeConfig->getValue('weltpixel_layerednavigation/sidebar/horizontal_box_shadow', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
}
}
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2025 WeltPixel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,50 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model;
class AttributeOptions extends \Magento\Framework\Model\AbstractModel implements \Magento\Framework\DataObject\IdentityInterface
{
const CACHE_TAG = 'weltpixel_ln_attribute_options';
const DISPLAY_OPTION_DEF_VAL = 0;
const DISPLAY_OPTION_OPEN_VAL = 1;
const VISIBLE_OPTIONS_DEF_VAL = 99;
const VISIBLE_OPTIONS_STEP_DEF_VAL = 99;
/**
* @var string
*/
protected $_cacheTag = 'weltpixel_ln_attribute_options';
/**
* @var string
*/
protected $_eventPrefix = 'weltpixel_ln_attribute_options';
protected function _construct()
{
$this->_init('WeltPixel\LayeredNavigation\Model\ResourceModel\AttributeOptions');
}
/**
* @return array|string[]
*/
public function getIdentities()
{
return [self::CACHE_TAG . '_' . $this->getId()];
}
/**
* @param $attributeId
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getDisplayOptionsByAttribute($attributeId) {
$this->_getResource()->loadDisplayOptionsByAttribute($this, $attributeId);
return $this;
}
}
@@ -0,0 +1,41 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
/**
* Class CategoryShowAs
* @package WeltPixel\LayeredNavigation\Model\Config\Source
*/
class CategoryShowAs implements ArrayInterface
{
/**
* @var array
*/
protected $_showAs = array(
0 => 'Closed',
1 => 'Fully Opened'
);
/**
* @return array
*/
public function toOptionArray()
{
$options = array();
foreach ($this->_showAs as $id => $showAs) :
$options[] = array(
'value' => $id,
'label' => $showAs
);
endforeach;
return $options;
}
}
@@ -0,0 +1,42 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
/**
* Class FilterButton
* @package WeltPixel\LayeredNavigation\Model\Config\Source
*/
class FilterButton implements ArrayInterface
{
/**
* @var array
*/
protected $_styles = array(
0 => 'Icon Only',
1 => 'Icon + Label',
2 => 'Label Only',
);
/**
* @return array
*/
public function toOptionArray()
{
$options = array();
foreach ($this->_styles as $id => $style) :
$options[] = array(
'value' => $id,
'label' => $style
);
endforeach;
return $options;
}
}
@@ -0,0 +1,42 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
/**
* Class FilterDisplay
* @package WeltPixel\LayeredNavigation\Model\Config\Source
*/
class FilterDisplay implements ArrayInterface
{
/**
* @var array
*/
protected $_styles = array(
0 => 'Close',
1 => 'Open',
2 => 'Expand',
);
/**
* @return array
*/
public function toOptionArray()
{
$options = array();
foreach ($this->_styles as $id => $style) :
$options[] = array(
'value' => $id,
'label' => $style
);
endforeach;
return $options;
}
}
@@ -0,0 +1,41 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
/**
* Class FilterShowHideState
* @package WeltPixel\LayeredNavigation\Model\Config\Source
*/
class FilterShowHideState implements ArrayInterface
{
/**
* @var array
*/
protected $_styles = [
'open' => 'Open',
'closed' => 'Closed',
];
/**
* @return array
*/
public function toOptionArray()
{
$options = [];
foreach ($this->_styles as $id => $style) :
$options[] = [
'value' => $id,
'label' => $style
];
endforeach;
return $options;
}
}
@@ -0,0 +1,73 @@
<?php
namespace WeltPixel\LayeredNavigation\Model\Config\Source;
use Magento\Eav\Model\Entity\Attribute\Source\SourceInterface;
use Magento\Framework\Data\OptionSourceInterface;
class HorizontalSidebarDesignVersion implements SourceInterface, OptionSourceInterface
{
/**
* block type
*/
const VERSION_1 = 'v1';
const VERSION_2 = 'v2';
const VERSION_3 = 'v3';
/**
* Prepare display options.
*
* @return array
*/
public function getAvailableModes()
{
return [
self::VERSION_1 => __('Version 1'),
self::VERSION_2 => __('Version 2'),
self::VERSION_3 => __('Version 3'),
];
}
/**
* Retrieve All options
*
* @return array
*/
public function getAllOptions()
{
$result = [];
foreach ($this->getAvailableModes() as $index => $value) {
$result[] = ['value' => $index, 'label' => $value];
}
return $result;
}
/**
* Retrieve Option value text
*
* @param string $value
* @return mixed
*/
public function getOptionText($value)
{
$options = $this->getAvailableModes();
return isset($options[$value]) ? $options[$value] : null;
}
/**
* Return array of options as value-label pairs
*
* @return array Format: array(array('value' => '<value>', 'label' => '<label>'), ...)
*/
public function toOptionArray()
{
return $this->getAllOptions();
}
}
@@ -0,0 +1,71 @@
<?php
namespace WeltPixel\LayeredNavigation\Model\Config\Source;
use Magento\Eav\Model\Entity\Attribute\Source\SourceInterface;
use Magento\Framework\Data\OptionSourceInterface;
class HorizontalSidebarFilterPosition implements SourceInterface, OptionSourceInterface
{
/**
* block type
*/
const LEFT = 'left';
const CENTER = 'center';
/**
* Prepare display options.
*
* @return array
*/
public function getAvailableModes()
{
return [
self::LEFT => __('Left'),
self::CENTER => __('Center')
];
}
/**
* Retrieve All options
*
* @return array
*/
public function getAllOptions()
{
$result = [];
foreach ($this->getAvailableModes() as $index => $value) {
$result[] = ['value' => $index, 'label' => $value];
}
return $result;
}
/**
* Retrieve Option value text
*
* @param string $value
* @return mixed
*/
public function getOptionText($value)
{
$options = $this->getAvailableModes();
return isset($options[$value]) ? $options[$value] : null;
}
/**
* Return array of options as value-label pairs
*
* @return array Format: array(array('value' => '<value>', 'label' => '<label>'), ...)
*/
public function toOptionArray()
{
return $this->getAllOptions();
}
}
@@ -0,0 +1,41 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
/**
* Class PriceFilter
* @package WeltPixel\LayeredNavigation\Model\Config\Source
*/
class PriceFilter implements ArrayInterface
{
/**
* @var array
*/
protected $_styles = array(
'1' => 'Default',
'2' => 'Slider'
);
/**
* @return array
*/
public function toOptionArray()
{
$options = array();
foreach ($this->_styles as $id => $style) :
$options[] = array(
'value' => $id,
'label' => $style
);
endforeach;
return $options;
}
}
@@ -0,0 +1,41 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
/**
* Class RatingFilterDisplay
* @package WeltPixel\LayeredNavigation\Model\Config\Source
*/
class RatingFilterDisplay implements ArrayInterface
{
/**
* @var array
*/
protected $_styles = array(
0 => 'Close',
1 => 'Open'
);
/**
* @return array
*/
public function toOptionArray()
{
$options = array();
foreach ($this->_styles as $id => $style) :
$options[] = array(
'value' => $id,
'label' => $style
);
endforeach;
return $options;
}
}
@@ -0,0 +1,43 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
/**
* Class SidebarStyle
* @package WeltPixel\LayeredNavigation\Model\Config\Source
*/
class SidebarStyle implements ArrayInterface
{
/**
* @var array
*/
protected $_styles = array(
'0' => 'Default',
'1' => 'Slide In',
'2' => 'Slide Down',
'3' => 'Horizontal View'
);
/**
* @return array
*/
public function toOptionArray()
{
$options = array();
foreach ($this->_styles as $id => $style) :
$options[] = array(
'value' => $id,
'label' => $style
);
endforeach;
return $options;
}
}
@@ -0,0 +1,120 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
use \Magento\Store\Model\StoreManagerInterface;
use \Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\View\Design\Theme\ThemeProviderInterface;
/**
* Class SlideDownFilterColumns
* @package WeltPixel\LayeredNavigation\Model\Config\Source
*/
class SlideDownFilterColumns implements ArrayInterface
{
/**
* @var array
*/
protected $_styles = array(
'99%' => '1 column',
'48.5%' => '2 columns',
'31.9%' => '3 columns',
'23.4%' => '4 columns',
'18.4%' => '5 columns',
'15.2%' => '6 columns',
);
/**
* @var array
*/
protected $_pearl_styles = array(
'99%' => '1 column',
'49%' => '2 columns',
'32.33%' => '3 columns',
'24%' => '4 columns',
'19%' => '5 columns',
'16.33%' => '6 columns',
);
/**
* @var StoreManagerInterface
*/
protected $storeManager;
/**
* @var ScopeConfigInterface
*/
protected $scopeConfig;
/** @var ThemeProviderInterface */
protected $themeProvider;
public function __construct(
StoreManagerInterface $storeManager,
ScopeConfigInterface $scopeConfig,
ThemeProviderInterface $themeProvider
)
{
$this->storeManager = $storeManager;
$this->scopeConfig = $scopeConfig;
$this->themeProvider = $themeProvider;
}
/**
* @return array
*/
public function toOptionArray()
{
$options = array();
if($this->_isPearlTheamActive()) {
foreach ($this->_pearl_styles as $id => $style) :
$options[] = array(
'value' => $id,
'label' => $style
);
endforeach;
} else {
foreach ($this->_styles as $id => $style) :
$options[] = array(
'value' => $id,
'label' => $style
);
endforeach;
}
return $options;
}
/**
* @return bool
* @throws \Exception
*/
protected function _isPearlTheamActive()
{
try {
$store = $this->storeManager->getStore();
$themeId = $this->scopeConfig->getValue(
\Magento\Framework\View\DesignInterface::XML_PATH_THEME_ID,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
$store->getId()
);
$theme = $this->themeProvider->getThemeById($themeId);
$themePath = $theme->getThemePath();
if (strpos($themePath, 'Pearl') !== false) {
return true;
}
return false;
} catch (\Exception $ex) {
throw new \Exception('Store with id or code ' . $store->getId() . ' not found.');
}
}
}
@@ -0,0 +1,41 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
/**
* Class SortBy
* @package WeltPixel\LayeredNavigation\Model\Config\Source
*/
class SortBy implements ArrayInterface
{
/**
* @var array
*/
protected $_styles = array(
'position' => 'Position',
'name' => 'Name'
);
/**
* @return array
*/
public function toOptionArray()
{
$options = array();
foreach ($this->_styles as $id => $style) :
$options[] = array(
'value' => $id,
'label' => $style
);
endforeach;
return $options;
}
}
+152
View File
@@ -0,0 +1,152 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Layer;
use Magento\Framework\App\RequestInterface;
use WeltPixel\LayeredNavigation\Model\AttributeOptions;
/**
* Class Filter
* @package WeltPixel\LayeredNavigation\Model\Layer
*/
class Filter
{
/** @var \Magento\Framework\App\RequestInterface */
protected $request;
/**
* @var AttributeOptions
*/
protected $_wpAttributeOptions;
/**
* @var array
*/
protected $_ids = [];
/**
* Filter constructor.
* @param RequestInterface $request
* @param AttributeOptions $attributeOptions
*/
public function __construct(
RequestInterface $request,
AttributeOptions $attributeOptions
)
{
$this->request = $request;
$this->_wpAttributeOptions = $attributeOptions;
}
/**
* Get option url. If it has been filtered, return removed url. Else return filter url
*
* @param \Magento\Catalog\Model\Layer\Filter\Item $item
* @return mixed
*/
public function getItemUrl($item)
{
if ($this->isSelected($item)) {
return $item->getRemoveUrl();
}
return $item->getUrl();
}
/**
* @param \Magento\Catalog\Model\Layer\Filter\AbstractFilter $filter
* @param bool|true $explode
* @return array|mixed
*/
public function getFilterValue($filter, $explode = true)
{
$filterValue = $this->request->getParam($filter->getRequestVar());
if (empty($filterValue)) {
return [];
}
return $explode ? explode(',', $filterValue) : $filterValue;
}
/**
* Checks whether the option reduces the number of results
*
* @param \Magento\Catalog\Model\Layer\Filter\AbstractFilter $filter
* @param int $optionCount Count of search results with this option
* @param int $totalSize Current search results count
* @return bool
*/
public function isOptionReducesResults($filter, $optionCount, $totalSize)
{
$result = $optionCount <= $totalSize;
if ($this->isShowZero($filter)) {
return $result;
}
return $optionCount && $result;
}
/**
* @param \Magento\Catalog\Model\Layer\Filter\AbstractFilter $filter
* @return bool
*/
public function isShowZero($filter)
{
return false;
}
/**
* @param $filter
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function isMainFilter($filter) {
if(empty($this->_ids)){
$this->_ids = $this->getStateAttributesIds($filter);
}
$isMulti = false;
if(count($this->_ids) <= 1) {
$isMulti = true;
if(!empty($this->_ids)) {
$isMulti = $this->isMultiselect($this->_ids[0]);
}
}
return $isMulti;
}
/**
* @param $attrId
*/
public function isMultiselect($attrId) {
$wpLnAttributeOptions = ($attrId) ? $this->_wpAttributeOptions->getDisplayOptionsByAttribute($attrId) : false;
$isMultiselect = ($wpLnAttributeOptions) ? $wpLnAttributeOptions->getIsMultiselect() : false;
return $isMultiselect;
}
/**
* @param Layer $layer
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function getStateAttributesIds($filter)
{
$layer = $filter->getLayer();
foreach ($layer->getState()->getFilters() as $filter) {
if ($model = $filter->getFilter()->getData('attribute_model')) {
$this->_ids[] = $model->getId();
}
}
return array_unique($this->_ids);
}
}
@@ -0,0 +1,361 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Layer\Filter;
use Magento\Catalog\Model\Layer\Filter\AbstractFilter;
use WeltPixel\LayeredNavigation\Helper\Data as LayerHelper;
use WeltPixel\LayeredNavigation\Model\Layer\Filter as LayerFilter;
use WeltPixel\LayeredNavigation\Model\AttributeOptions;
/**
* Class Attribute
* @package WeltPixel\LayeredNavigation\Model\Layer\Filter
*/
class Attribute extends AbstractFilter
{
/**
* @var LayerHelper
*/
protected $_moduleHelper;
/**
* @var bool
*/
protected $_isFilter = true;
/**
* @var \Magento\Framework\Filter\StripTags
*/
protected $tagFilter;
/**
* @var LayerFilter
*/
protected $_layerFilter;
/**
* @var AttributeOptions
*/
protected $_wpAttributeOptions;
/**
* @var
*/
protected $_requestParamVal;
/**
* Resource instance
*
* @var \Magento\Catalog\Model\ResourceModel\Layer\Filter\Attribute
*/
protected $_resource;
/**
* @var
*/
protected $_originalCollection;
/**
* @var \Magento\Framework\Stdlib\StringUtils
*/
protected $string;
/**
* @var int
*/
protected $selectedOptionsCounter = 0;
/**
* Attribute constructor.
* @param \Magento\Catalog\Model\Layer\Filter\ItemFactory $filterItemFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Catalog\Model\Layer $layer
* @param \Magento\Catalog\Model\Layer\Filter\Item\DataBuilder $itemDataBuilder
* @param \Magento\Framework\Filter\StripTags $tagFilter
* @param \Magento\Catalog\Model\ResourceModel\Layer\Filter\AttributeFactory $filterAttributeFactory
* @param LayerHelper $moduleHelper
* @param LayerFilter $layerFilter
* @param AttributeOptions $attributeOptions
* @param \Magento\Framework\Stdlib\StringUtils $string
* @param array $data
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function __construct(
\Magento\Catalog\Model\Layer\Filter\ItemFactory $filterItemFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\Layer $layer,
\Magento\Catalog\Model\Layer\Filter\Item\DataBuilder $itemDataBuilder,
\Magento\Framework\Filter\StripTags $tagFilter,
\Magento\Catalog\Model\ResourceModel\Layer\Filter\AttributeFactory $filterAttributeFactory,
LayerHelper $moduleHelper,
LayerFilter $layerFilter,
AttributeOptions $attributeOptions,
\Magento\Framework\Stdlib\StringUtils $string,
array $data = []
)
{
parent::__construct(
$filterItemFactory,
$storeManager,
$layer,
$itemDataBuilder,
$data
);
$this->_resource = $filterAttributeFactory->create();
$this->tagFilter = $tagFilter;
$this->_moduleHelper = $moduleHelper;
$this->_layerFilter = $layerFilter;
$this->_wpAttributeOptions = $attributeOptions;
$this->string = $string;
}
/**
* @inheritdoc
*/
public function apply(\Magento\Framework\App\RequestInterface $request)
{
if (!$this->_moduleHelper->isEnabled()) {
return $this->_getBaseApply($request);
}
$attributeValue = $request->getParam($this->_requestVar);
if (empty($attributeValue)) {
$this->_isFilter = false;
return $this;
}
$this->_requestParamVal = $this->_requestVar;
$attributeValue = explode(',', $attributeValue);
$this->selectedOptionsCounter = count($attributeValue);
$state = $this->getLayer()->getState();
foreach ($attributeValue as $value) {
$label = $this->getOptionText($value);
$state->addFilter($this->_createItem($label, $value));
}
$attribute = $this->getAttributeModel();
if (!$this->isMultiselect($attribute->getId()) && count($attributeValue) > 1) {
$attributeValue = array_slice($attributeValue, 0, 1);
}
/** @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $productCollection */
$productCollection = $this->getLayer()->getProductCollection();
if(!$this->_originalCollection) {
$this->_originalCollection = $productCollection->getCollectionClone();
}
if (count($attributeValue) > 1) {
if($this->_moduleHelper->isElasticOrOpenSearchEngine()) {
$productCollection->addFieldToFilter($attribute->getAttributeCode(), $attributeValue);
}
else {
$productCollection->addFieldToFilter($attribute->getAttributeCode(), ['in' => $attributeValue]);
}
} else {
$productCollection->addFieldToFilter($attribute->getAttributeCode(), $attributeValue[0]);
}
return $this;
}
/**
* Retrieve resource instance
*
* @return \Magento\Catalog\Model\ResourceModel\Layer\Filter\Attribute
*/
protected function _getResource()
{
return $this->_resource;
}
/**
* @inheritdoc
*/
protected function _getItemsData()
{
if (!$this->_moduleHelper->isEnabled()) {
return $this->_getBaseItemsData();
}
$attribute = $this->getAttributeModel();
$wpLnAttributeOptions = ($attribute->getId()) ? $this->_wpAttributeOptions->getDisplayOptionsByAttribute($attribute->getId()) : false;
if(!$wpLnAttributeOptions->getIsMultiselect() && $this->_isFilter) {
return [];
}
/** @var \WeltPixel\LayeredNavigation\Model\ResourceModel\Fulltext\Collection $productCollection */
$productCollection = $this->getLayer()->getProductCollection();
if ($this->_isFilter && ( $this->_layerFilter->isMainFilter($this) || $wpLnAttributeOptions->getIsMultiselect())) {
$productCollection = $productCollection->getCollectionClone()
->removeAttributeSearch($attribute->getAttributeCode());
}
$optionsFacetedData = $productCollection->getFacetedData($attribute->getAttributeCode());
if (count($optionsFacetedData) === 0
&& $this->getAttributeIsFilterable($attribute) !== static::ATTRIBUTE_OPTIONS_ONLY_WITH_RESULTS
) {
return $this->itemDataBuilder->build();
}
$productSize = $productCollection->getSize();
$itemData = [];
$checkCount = false;
$options = $attribute->getFrontend()->getSelectOptions();
$counter = false;
foreach ($options as $option) {
$sorted = false;
if (empty($option['value'])) {
continue;
}
$value = $option['value'];
if($counter) {
$count = isset($counter[$value]) ? (int)$counter[$value] : 0;
} else {
$count = isset($optionsFacetedData[$value]['count']) ? (int)$optionsFacetedData[$value]['count'] : 0;
}
// Check filter type
if ($this->getAttributeIsFilterable($attribute) == static::ATTRIBUTE_OPTIONS_ONLY_WITH_RESULTS && (!$this->_layerFilter->isOptionReducesResults($this, $count, $productSize)) && $count == 0) {
continue;
}
if ($count > 0) {
$checkCount = true;
}
$itemData[] = [
'label' => $this->tagFilter->filter($option['label']),
'value' => $value,
'count' => $count
];
}
if ($checkCount) {
if ($wpLnAttributeOptions->getSortBy() == 2) {
usort($itemData, [$this, '_compareAz']);
$sorted = true;
}
foreach ($itemData as $item) {
$this->itemDataBuilder->addItemData($item['label'], $item['value'], $item['count']);
}
}
if ($wpLnAttributeOptions->getSortBy() == 2 && !$sorted) {
usort($options, [$this, '_compareAz']);
}
return $this->itemDataBuilder->build();
}
/**
* return attribute custom 'is_multiselect' option
*
* @param $attrId
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function isMultiselect($attrId)
{
$wpLnAttributeOptions = ($attrId) ? $this->_wpAttributeOptions->getDisplayOptionsByAttribute($attrId) : false;
$isMultiselect = ($wpLnAttributeOptions) ? $wpLnAttributeOptions->getIsMultiselect() : false;
return $isMultiselect;
}
/**
* @param $a
* @param $b
* @return int
*/
protected function _compareAz($a, $b)
{
return strcmp($a["label"], $b["label"]);
}
/**
* @param $request
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function _getBaseApply($request){
$attributeValue = $request->getParam($this->_requestVar);
if (empty($attributeValue) && !is_numeric($attributeValue)) {
return $this;
}
$attribute = $this->getAttributeModel();
/** @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $productCollection */
$productCollection = $this->getLayer()
->getProductCollection();
$productCollection->addFieldToFilter($attribute->getAttributeCode(), $attributeValue);
$label = $this->getOptionText($attributeValue);
$this->getLayer()
->getState()
->addFilter($this->_createItem($label, $attributeValue));
$this->setItems([]); // set items to disable show filtering
return $this;
}
/**
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function _getBaseItemsData(){
$attribute = $this->getAttributeModel();
$this->_requestVar = $attribute->getAttributeCode();
$options = $attribute->getFrontend()->getSelectOptions();
$optionsCount = $this->_getResource()->getCount($this);
foreach ($options as $option) {
if (is_array($option['value'])) {
continue;
}
if ($this->string->strlen($option['value'])) {
// Check filter type
if ($this->getAttributeIsFilterable($attribute) == self::ATTRIBUTE_OPTIONS_ONLY_WITH_RESULTS) {
if (!empty($optionsCount[$option['value']])) {
$this->itemDataBuilder->addItemData(
$this->tagFilter->filter($option['label']),
$option['value'],
$optionsCount[$option['value']]
);
}
} else {
$this->itemDataBuilder->addItemData(
$this->tagFilter->filter($option['label']),
$option['value'],
isset($optionsCount[$option['value']]) ? $optionsCount[$option['value']] : 0
);
}
}
}
return $this->itemDataBuilder->build();
}
/**
* @return int
*/
public function getSelectedOptionsCounter()
{
return $this->selectedOptionsCounter;
}
}
@@ -0,0 +1,148 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Layer\Filter;
use Magento\CatalogSearch\Model\Layer\Filter\Category as AbstractFilter;
use WeltPixel\LayeredNavigation\Helper\Data as LayerHelper;
use WeltPixel\LayeredNavigation\Model\Layer\Filter as LayerFilter;
/**
* Class Category
* @package WeltPixel\LayeredNavigation\Model\Layer\Filter
*/
class Category extends AbstractFilter
{
/** @var \WeltPixel\LayeredNavigation\Helper\Data */
protected $_moduleHelper;
/** @var bool Is Filterable Flag */
protected $_isFilter = false;
/** @var \Magento\Framework\Escaper */
private $escaper;
/** @var \Magento\Catalog\Model\Layer\Filter\DataProvider\Category */
private $dataProvider;
/**
* Category constructor.
* @param \Magento\Catalog\Model\Layer\Filter\ItemFactory $filterItemFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Catalog\Model\Layer $layer
* @param \Magento\Catalog\Model\Layer\Filter\Item\DataBuilder $itemDataBuilder
* @param \Magento\Framework\Escaper $escaper
* @param \Magento\Catalog\Model\Layer\Filter\DataProvider\CategoryFactory $categoryDataProviderFactory
* @param LayerHelper $moduleHelper
* @param LayerFilter $layerFilter
* @param array $data
*/
public function __construct(
\Magento\Catalog\Model\Layer\Filter\ItemFactory $filterItemFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\Layer $layer,
\Magento\Catalog\Model\Layer\Filter\Item\DataBuilder $itemDataBuilder,
\Magento\Framework\Escaper $escaper,
\Magento\Catalog\Model\Layer\Filter\DataProvider\CategoryFactory $categoryDataProviderFactory,
LayerHelper $moduleHelper,
LayerFilter $layerFilter,
array $data = []
)
{
parent::__construct(
$filterItemFactory,
$storeManager,
$layer,
$itemDataBuilder,
$escaper,
$categoryDataProviderFactory,
$data
);
$this->escaper = $escaper;
$this->_moduleHelper = $moduleHelper;
$this->_layerFilter = $layerFilter;
$this->dataProvider = $categoryDataProviderFactory->create(['layer' => $this->getLayer()]);
}
/**
* @inheritdoc
*/
public function apply(\Magento\Framework\App\RequestInterface $request)
{
if (!$this->_moduleHelper->isEnabled()) {
return parent::apply($request);
}
$categoryId = $request->getParam($this->_requestVar);
if (empty($categoryId)) {
return $this;
}
$categoryIds = [];
foreach (explode(',', $categoryId) as $key => $id) {
$this->dataProvider->setCategoryId($id);
$categoryIds[] = $id;
if ($this->dataProvider->isValid()) {
$category = $this->dataProvider->getCategory();
if ($request->getParam('id') != $id) {
$this->getLayer()->getState()->addFilter($this->_createItem($category->getName(), $id));
}
}
}
if (sizeof($categoryIds)) {
$this->_isFilter = true;
$this->getLayer()->getProductCollection()->addLayerCategoryFilter($categoryIds);
}
return $this;
}
/**
* @return array
* @throws \Magento\Framework\Exception\StateException
*/
protected function _getItemsData()
{
if (!$this->_moduleHelper->isEnabled()) {
return parent::_getItemsData();
}
/** @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $productCollection */
$productCollection = $this->getLayer()->getProductCollection();
if ($this->_isFilter) {
$productCollection = $productCollection->getCollectionClone()
->removeAttributeSearch('category_ids');
}
$optionsFacetedData = $productCollection->getFacetedData('category');
$category = $this->dataProvider->getCategory();
$categories = $category->getChildrenCategories();
$collectionSize = $productCollection->getSize();
if ($category->getIsActive()) {
foreach ($categories as $category) {
$count = isset($optionsFacetedData[$category->getId()]) ? $optionsFacetedData[$category->getId()]['count'] : 0;
if ($category->getIsActive()
&& $this->_layerFilter->isOptionReducesResults($this, $count, $collectionSize)
) {
$this->itemDataBuilder->addItemData(
$this->escaper->escapeHtml($category->getName()),
$category->getId(),
$count
);
}
}
}
return $this->itemDataBuilder->build();
}
}
@@ -0,0 +1,341 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Layer\Filter;
use Magento\CatalogSearch\Model\Layer\Filter\Price as AbstractFilter;
use WeltPixel\LayeredNavigation\Helper\Data as LayerHelper;
use WeltPixel\LayeredNavigation\Model\AttributeOptions;
/**
* Class Price
* @package WeltPixel\LayeredNavigation\Model\Layer\Filter
*/
class Price extends AbstractFilter
{
/** @var \WeltPixel\LayeredNavigation\Helper\Data */
protected $_moduleHelper;
/** @var array|null Filter value */
protected $_filterVal = null;
/** @var \Magento\Tax\Helper\Data */
protected $_taxHelper;
/** @var \Magento\Catalog\Model\Layer\Filter\DataProvider\Price */
private $dataProvider;
/** @var \Magento\Framework\Pricing\PriceCurrencyInterface */
private $priceCurrency;
/** @var \Magento\Framework\Registry */
protected $_registry;
protected $_scopeConfig;
/**
* @var AttributeOptions
*/
protected $_wpAttributeOptions;
/**
* @var \WeltPixel\LayeredNavigation\Helper\Data
*/
protected $_wpHelper;
/**
* @var int
*/
protected $selectedOptionsCounter = 0;
/**
* Price constructor.
* @param \Magento\Catalog\Model\Layer\Filter\ItemFactory $filterItemFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Catalog\Model\Layer $layer
* @param \Magento\Catalog\Model\Layer\Filter\Item\DataBuilder $itemDataBuilder
* @param \Magento\Catalog\Model\ResourceModel\Layer\Filter\Price $resource
* @param \Magento\Customer\Model\Session $customerSession
* @param \Magento\Framework\Search\Dynamic\Algorithm $priceAlgorithm
* @param \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency
* @param \Magento\Catalog\Model\Layer\Filter\Dynamic\AlgorithmFactory $algorithmFactory
* @param \Magento\Catalog\Model\Layer\Filter\DataProvider\PriceFactory $dataProviderFactory
* @param \Magento\Tax\Helper\Data $taxHelper
* @param LayerHelper $moduleHelper
* @param AttributeOptions $attributeOptions
* @param \WeltPixel\LayeredNavigation\Helper\Data $wpHelper
* @param \Magento\Framework\Registry $registry
* @param array $data
*/
public function __construct(
\Magento\Catalog\Model\Layer\Filter\ItemFactory $filterItemFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\Layer $layer,
\Magento\Catalog\Model\Layer\Filter\Item\DataBuilder $itemDataBuilder,
\Magento\Catalog\Model\ResourceModel\Layer\Filter\Price $resource,
\Magento\Customer\Model\Session $customerSession,
\Magento\Framework\Search\Dynamic\Algorithm $priceAlgorithm,
\Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency,
\Magento\Catalog\Model\Layer\Filter\Dynamic\AlgorithmFactory $algorithmFactory,
\Magento\Catalog\Model\Layer\Filter\DataProvider\PriceFactory $dataProviderFactory,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Tax\Helper\Data $taxHelper,
LayerHelper $moduleHelper,
AttributeOptions $attributeOptions,
\WeltPixel\LayeredNavigation\Helper\Data $wpHelper,
\Magento\Framework\Registry $registry,
array $data = []
)
{
parent::__construct(
$filterItemFactory,
$storeManager,
$layer,
$itemDataBuilder,
$resource,
$customerSession,
$priceAlgorithm,
$priceCurrency,
$algorithmFactory,
$dataProviderFactory,
$data
);
$this->priceCurrency = $priceCurrency;
$this->dataProvider = $dataProviderFactory->create(['layer' => $this->getLayer()]);
$this->_moduleHelper = $moduleHelper;
$this->_taxHelper = $taxHelper;
$this->_registry = $registry;
$this->_scopeConfig = $scopeConfig;
$this->_wpAttributeOptions = $attributeOptions;
$this->_wpHelper = $wpHelper;
}
/**
* @inheritdoc
*/
public function apply(\Magento\Framework\App\RequestInterface $request)
{
$priceRangeCalculation = $this->_scopeConfig->getValue(
\Magento\Catalog\Model\Layer\Filter\Dynamic\AlgorithmFactory::XML_PATH_RANGE_CALCULATION,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
if($priceRangeCalculation != 'auto') {
return parent::apply($request);
}
$filterEntry = [];
if (!$this->_moduleHelper->isEnabled()) {
return parent::apply($request);
}
/**
* Filter must be string: $fromPrice-$toPrice
*/
$filter = $strFilter = $request->getParam($this->getRequestVar());
if (!$filter || is_array($filter)) {
return $this;
}
$collection = $this->getLayer()->getProductCollection();
$baseCollection = clone $collection;
$currentCatId = $this->_registry->registry('current_category') ? $this->_registry->registry('current_category')->getId() : false;
$priceFilter = $this->_registry->registry('price_filter') ?: [];
if ($currentCatId) {
if (!array_key_exists($currentCatId, $priceFilter)) {
$basePriceData = [
'min' => $baseCollection->getMinPrice(),
'max' => $baseCollection->getMaxPrice()
];
$filterEntry = [
$currentCatId => $basePriceData
];
$this->_registry->register('price_filter', $filterEntry);
}
}
$filterParams = explode(',', $filter);
$this->selectedOptionsCounter = count($filterParams);
$attribute = $this->getAttributeModel();
$wpLnAttributeOptions = ($attribute->getId()) ? $this->_wpAttributeOptions->getDisplayOptionsByAttribute($attribute->getId()) : false;
if (!$this->_wpHelper->getPriceIsSliderMode() && $wpLnAttributeOptions->getIsMultiselect()) {
$filterConditions = [];
foreach ($filterParams as $filterParam) {
$filter = $this->dataProvider->validateFilter($filterParam);
if (!$filter) {
continue;
}
$this->dataProvider->setInterval($filter);
$priorFilters = $this->dataProvider->getPriorFilters($filterParams);
if ($priorFilters) {
$this->dataProvider->setPriorIntervals($filterParams);
}
list($from, $to) = $this->_filterVal = $filter;
$filterConditions[] = [
'attribute' => 'price',
['from' => $from, 'to' => $to]
];
$this->getLayer()->getState()->addFilter(
$this->_createItem($this->_renderRangeLabel(empty($from) ? 0 : $from, $to), $filter)
);
}
$this->getLayer()->getProductCollection()->addAttributeToFilter(
$filterConditions
);
} else {
$filter = $this->dataProvider->validateFilter($filterParams[0]);
if (!$filter) {
return $this;
}
$this->dataProvider->setInterval($filter);
$priorFilters = $this->dataProvider->getPriorFilters($filterParams);
if ($priorFilters) {
$this->dataProvider->setPriorIntervals($priorFilters);
}
list($from, $to) = $this->_filterVal = $filter;
$this->getLayer()->getProductCollection()->addFieldToFilter(
'price',
['from' => $from, 'to' => $to]
);
$this->getLayer()->getState()->addFilter(
$this->_createItem($this->_renderRangeLabel(empty($from) ? 0 : $from, $to), $filter)
);
}
return $this;
}
/**
* @inheritdoc
*/
protected function _renderRangeLabel($fromPrice, $toPrice, $isLast = false)
{
if (!$this->_moduleHelper->isEnabled()) {
return parent::_renderRangeLabel($fromPrice, $toPrice, $isLast);
}
$formattedFromPrice = $this->priceCurrency->format($fromPrice);
if ($toPrice === '' || $isLast) {
return __('%1 and above', $formattedFromPrice);
} elseif ($fromPrice == $toPrice && $this->dataProvider->getOnePriceIntervalValue()) {
return $formattedFromPrice;
} else {
return __('%1 - %2', $formattedFromPrice, $this->priceCurrency->format($toPrice));
}
}
/**
* Get data array for building attribute filter items
*
* @return array
*
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function _getItemsData()
{
/*
if (!$this->_moduleHelper->isEnabled()) {
return parent::_getItemsData();
}
*/
$attribute = $this->getAttributeModel();
$this->_requestVar = $attribute->getAttributeCode();
$wpLnAttributeOptions = ($attribute->getId()) ? $this->_wpAttributeOptions->getDisplayOptionsByAttribute($attribute->getId()) : false;
if (!$this->_wpHelper->getPriceIsSliderMode() && !$wpLnAttributeOptions->getIsMultiselect() && $this->_filterVal) {
return [];
}
/** @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $productCollection */
$productCollection = $this->getLayer()->getProductCollection();
if ($this->_filterVal) {
/** @type \WeltPixel\LayeredNavigation\Model\ResourceModel\Fulltext\Collection $productCollectionClone */
$productCollection = $productCollection->getCollectionClone()
->removeAttributeSearch(['price.from', 'price.to']);
}
$facets = $productCollection->getFacetedData($attribute->getAttributeCode());
$data = [];
if (count($facets) > 1) {
$lastFacet = array_key_last($facets);
foreach ($facets as $key => $aggregation) {
$count = $aggregation['count'];
if (strpos($key, '_') === false) {
continue;
}
$isLast = $lastFacet === $key;
$data[] = $this->prepareData($key, $count, $wpLnAttributeOptions->getIsMultiselect(), $isLast);
}
}
return $data;
}
/**
* @param string $key
* @param int $count
* @param bool $isMultiSelect
* @param boolean $isLast
* @return array
*/
private function prepareData($key, $count, $isMultiSelect, $isLast = false)
{
list($from, $to) = explode('_', $key);
if ($from == '*') {
$from = $this->getFrom($to);
}
if ($to == '*') {
$to = $this->getTo($to);
}
$label = $this->_renderRangeLabel(
empty($from) ? 0 : $from * $this->getCurrencyRate(),
empty($to) ? $to : $to * $this->getCurrencyRate(),
$isLast
);
$value = $from . '-' . $to;
if (!$isMultiSelect) {
$value .= $this->dataProvider->getAdditionalRequestData();
}
$data = [
'label' => $label,
'value' => $value,
'count' => $count,
'from' => $from,
'to' => $to,
];
return $data;
}
/**
* @return int
*/
public function getSelectedOptionsCounter()
{
return $this->selectedOptionsCounter;
}
}
@@ -0,0 +1,236 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Nagy Attila @ Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Layer\Filter;
use Magento\Catalog\Model\Layer;
use WeltPixel\LayeredNavigation\Helper\Data as LayerHelper;
/**
* Layer category filter
*
* @author Magento Core Team <core@magentocommerce.com>
*/
class Rating extends \Magento\Catalog\Model\Layer\Filter\AbstractFilter
{
/**
* Active Category Id
*
* @var int
*/
protected $_categoryId;
/**
* Applied Category
*
* @var \Magento\Catalog\Model\Category
*/
protected $_appliedCategory;
/**
* Core data
*
* @var \Magento\Framework\Escaper
*/
protected $_escaper;
/**
* Core registry
*
* @var \Magento\Framework\Registry
*/
protected $_coreRegistry;
/**
* @var CategoryDataProvider
*/
private $dataProvider;
/**
* @var \WeltPixel\LayeredNavigation\Helper\Data
*/
protected $_wpHelper;
/**
* @var int
*/
protected $selectedOptionsCounter = 0;
/**
* Rating constructor.
* @param \Magento\Framework\Registry $coreRegistry
* @param Layer\Filter\ItemFactory $filterItemFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param Layer $layer
* @param Layer\Filter\Item\DataBuilder $itemDataBuilder
* @param \Magento\Framework\Escaper $escaper
* @param LayerHelper $moduleHelper
* @param array $data
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function __construct(
\Magento\Framework\Registry $coreRegistry,
\Magento\Catalog\Model\Layer\Filter\ItemFactory $filterItemFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\Layer $layer,
\Magento\Catalog\Model\Layer\Filter\Item\DataBuilder $itemDataBuilder,
\Magento\Framework\Escaper $escaper,
LayerHelper $moduleHelper,
array $data = []
) {
parent::__construct($filterItemFactory, $storeManager, $layer, $itemDataBuilder, $data);
$this->_escaper = $escaper;
$this->_wpHelper = $moduleHelper;
$this->_requestVar = $this->_wpHelper->getRatingParamLabel();
$this->_coreRegistry = $coreRegistry;
}
/**
* Apply category filter to layer
*
* @param \Magento\Framework\App\RequestInterface $request
* @return $this
*/
public function apply(\Magento\Framework\App\RequestInterface $request)
{
/**
* Filter must be string: $fromPrice-$toPrice
*/
$filter = $request->getParam($this->getRequestVar());
if (!$filter) {
return $this;
}
$filters = explode(',',$filter);
$this->selectedOptionsCounter = count($filters);
$collection = $this->getLayer()->getProductCollection();
$noRatingCollection = $collection->getCollectionClone();
$this->_coreRegistry->register('no_rating_coll', $noRatingCollection);
$collection->getSelect()->joinLeft(array('rating'=> 'rating_option_vote_aggregated'),'e.entity_id =rating.entity_pk_value',array("percent"))
->where("rating.store_id = ?", $this->_storeManager->getStore()->getId())
->group('e.entity_id');
foreach($filters as $reqFilter){
list($from,$to) = explode('-', $reqFilter);
$conditionArr[] = new \Zend_Db_Expr("rating.percent BETWEEN ".$from." AND ".$to);
}
$condString = '';
foreach($conditionArr as $condition) {
$condString .= " {$condition} OR";
}
$collection->getSelect()->where(substr($condString, 0, -2));
foreach($filters as $reqFilter) {
$state = $this->_createItem($this->getLabelHtml($reqFilter), $reqFilter)
->setVar($this->_requestVar);
$this->getLayer()->getState()->addFilter($state);
}
$collection->getSize();
return $this;
}
/**
* @return \Magento\Framework\Phrase|string
*/
public function getName()
{
$name = ($this->_wpHelper->getRatingFilterName()) ? $this->_wpHelper->getRatingFilterName() : 'Rating';
return __($name);
}
/**
* Get data array for building attribute filter items
*
* @throws \Magento\Framework\Exception\LocalizedException
* @return array
*/
protected function _getItemsData()
{
$collection = $this->_coreRegistry->registry('no_rating_coll');
if (!$this->_wpHelper->isRatingFilterMultiselect() && isset($collection) ) {
return [];
}
$facets = array(
'0-20' => $this->_getRatingLabelHtml(1),
'21-40' => $this->_getRatingLabelHtml(2),
'41-60' => $this->_getRatingLabelHtml(3),
'61-80' => $this->_getRatingLabelHtml(4),
'81-100' => $this->_getRatingLabelHtml(5),
);
if (count($facets) > 1) { // two range minimum
$i=1;
foreach ($facets as $key => $label) {
if (!$collection) {
$collection = $this->getLayer()->getProductCollection();
}
$clonedCollection = clone $collection;
$count = $this->prepareData($key, $clonedCollection, $i);
$i++;
if($count > 0) {
$this->itemDataBuilder->addItemData(
$label,
$key,
$count
);
}
}
}
return $this->itemDataBuilder->build();
}
/**
* @param string $key
* @param int $count
* @return array
*/
private function prepareData($filter,$collection,$i)
{
$filter = explode('-', $filter);
list($from, $to) = $filter;
$collection->clear();
/** @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $productCollection */
$collection->getSelect()->joinLeft(array('rating'.$i=> 'rating_option_vote_aggregated'),'e.entity_id =rating'.$i.'.entity_pk_value',array("percent"))
->where("rating".$i.".percent between ".$from." and ".$to)
->where("rating".$i.".store_id = ?", $this->_storeManager->getStore()->getId())
->group('e.entity_id');
return $collection->getSize();
}
/**
* @param $countStars
* @return string
*/
protected function _getRatingLabelHtml($countStars)
{
$html = '<div class="rating-summary" style="display: inline-block;margin-top: -5px;">
<div class="rating-result" title="up to '.$countStars*20 .'%"">
<span style="width:'.$countStars*20 .'%"></span>
</div>
</div>';
return $html;
}
/**
* @return int
*/
public function getSelectedOptionsCounter()
{
return $this->selectedOptionsCounter;
}
}
@@ -0,0 +1,75 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\ResourceModel;
/**
* Class AttributeOptions
* @package WeltPixel\LayeredNavigation\Model\ResourceModel
*/
class AttributeOptions extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
/**
* @var array
*/
protected $loadedAttributes = [];
/**
* AttributeOptions constructor.
* @param \Magento\Framework\Model\ResourceModel\Db\Context $context
*/
public function __construct(
\Magento\Framework\Model\ResourceModel\Db\Context $context
)
{
parent::__construct($context);
}
protected function _construct()
{
$this->_init('weltpixel_ln_attribute_options', 'id');
}
/**
* Load Attribute display option by attribute_id & store_id
*
* @param \WeltPixel\LayeredNavigation\Model\AttributeOptions $attributeOptions
* @param $attributeId
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function loadDisplayOptionsByAttribute(
\WeltPixel\LayeredNavigation\Model\AttributeOptions $attributeOptions,
$attributeId
) {
if (isset($this->loadedAttributes[$attributeId])) {
$attributeOptions->setData($this->loadedAttributes[$attributeId]->getData());
return $this;
}
$connection = $this->getConnection();
$bind = [
'attribute_id' => $attributeId
];
$select = $connection->select()->from(
$this->getMainTable(),
[$this->getIdFieldName()]
)->where(
'attribute_id = :attribute_id'
);
$lineId = $connection->fetchOne($select, $bind);
if ($lineId) {
$this->load($attributeOptions, $lineId);
} else {
$attributeOptions->setData([]);
}
$this->loadedAttributes[$attributeId] = clone $attributeOptions;
}
}
@@ -0,0 +1,31 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\ResourceModel\AttributeOptions;
/**
* Class Collection
* @package WeltPixel\LayeredNavigation\Model\ResourceModel\AttributeOptions
*/
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
protected $_idFieldName = 'id';
protected $_eventPrefix = 'weltpixel_ln_atribute_options_collection';
protected $_eventObject = 'attribute_options_collection';
/**
* Define resource model
*
* @return void
*/
protected function _construct()
{
$this->_init('WeltPixel\LayeredNavigation\Model\AttributeOptions', 'WeltPixel\LayeredNavigation\Model\ResourceModel\AttributeOptions');
}
}
@@ -0,0 +1,587 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\ResourceModel\Fulltext;
use Magento\CatalogSearch\Model\Search\RequestGenerator;
use Magento\Framework\Api\Search\SearchResultFactory;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\DB\Select;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\StateException;
use Magento\Framework\Search\Adapter\Mysql\TemporaryStorage;
use Magento\Framework\Search\Request\EmptyRequestDataException;
use Magento\Store\Model\ScopeInterface;
use Magento\CatalogSearch\Model\ResourceModel\EngineInterface;
/**
* Class Collection
* @package WeltPixel\LayeredNavigation\Model\ResourceModel\Fulltext
*/
class Collection extends \Magento\Catalog\Model\ResourceModel\Product\Collection
{
/** @var \WeltPixel\LayeredNavigation\Model\ResourceModel\Fulltext\Collection|null Clone collection */
public $collectionClone = null;
/** @var string */
private $queryText;
/** @var string|null */
private $order = null;
/** @var string */
private $searchRequestName;
/** @var \Magento\Framework\Search\Adapter\Mysql\TemporaryStorageFactory */
private $temporaryStorageFactory;
/** @var \Magento\Search\Api\SearchInterface */
private $search;
/** @var \WeltPixel\LayeredNavigation\Model\ResourceModel\Search\SearchCriteriaBuilder */
private $searchCriteriaBuilder;
/** @var \Magento\Framework\Api\Search\SearchResultInterface */
private $searchResult;
/** @var \Magento\Framework\Api\FilterBuilder */
private $filterBuilder;
/* @var \Magento\Framework\App\Config\ScopeConfigInterface */
protected $_scopeConfig;
/** @var \Magento\Framework\App\ProductMetadataInterface */
protected $_productMetadata;
/** @var */
protected $_categoryId;
/** @var */
protected $_isTwoOne;
/**
* @var SearchResultFactory
*/
protected $searchResultFactory;
/**
* Collection constructor.
* @param \Magento\Framework\Data\Collection\EntityFactory $entityFactory
* @param \Psr\Log\LoggerInterface $logger
* @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy
* @param \Magento\Framework\Event\ManagerInterface $eventManager
* @param \Magento\Eav\Model\Config $eavConfig
* @param \Magento\Framework\App\ResourceConnection $resource
* @param \Magento\Eav\Model\EntityFactory $eavEntityFactory
* @param \Magento\Catalog\Model\ResourceModel\Helper $resourceHelper
* @param \Magento\Framework\Validator\UniversalFactory $universalFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Framework\Module\Manager $moduleManager
* @param \Magento\Catalog\Model\Indexer\Product\Flat\State $catalogProductFlatState
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Magento\Catalog\Model\Product\OptionFactory $productOptionFactory
* @param \Magento\Catalog\Model\ResourceModel\Url $catalogUrl
* @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate
* @param \Magento\Customer\Model\Session $customerSession
* @param \Magento\Framework\Stdlib\DateTime $dateTime
* @param \Magento\Customer\Api\GroupManagementInterface $groupManagement
* @param \Magento\Framework\Search\Adapter\Mysql\TemporaryStorageFactory $temporaryStorageFactory
* @param \Magento\Framework\App\ProductMetadataInterface $productMetadata
* @param \Magento\Framework\DB\Adapter\AdapterInterface|null $connection
* @param string $searchRequestName
* @param SearchResultFactory|null $searchResultFactory
*/
public function __construct(
\Magento\Framework\Data\Collection\EntityFactory $entityFactory,
\Psr\Log\LoggerInterface $logger,
\Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
\Magento\Framework\Event\ManagerInterface $eventManager,
\Magento\Eav\Model\Config $eavConfig,
\Magento\Framework\App\ResourceConnection $resource,
\Magento\Eav\Model\EntityFactory $eavEntityFactory,
\Magento\Catalog\Model\ResourceModel\Helper $resourceHelper,
\Magento\Framework\Validator\UniversalFactory $universalFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\Module\Manager $moduleManager,
\Magento\Catalog\Model\Indexer\Product\Flat\State $catalogProductFlatState,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Catalog\Model\Product\OptionFactory $productOptionFactory,
\Magento\Catalog\Model\ResourceModel\Url $catalogUrl,
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
\Magento\Customer\Model\Session $customerSession,
\Magento\Framework\Stdlib\DateTime $dateTime,
\Magento\Customer\Api\GroupManagementInterface $groupManagement,
\Magento\Framework\Search\Adapter\Mysql\TemporaryStorageFactory $temporaryStorageFactory,
\Magento\Framework\App\ProductMetadataInterface $productMetadata,
?\Magento\Framework\DB\Adapter\AdapterInterface $connection = null,
$searchRequestName = 'catalog_view_container',
?SearchResultFactory $searchResultFactory = null
)
{
$this->searchResultFactory = $searchResultFactory ?? ObjectManager::getInstance()->get(SearchResultFactory::class);
parent::__construct(
$entityFactory,
$logger,
$fetchStrategy,
$eventManager,
$eavConfig,
$resource,
$eavEntityFactory,
$resourceHelper,
$universalFactory,
$storeManager,
$moduleManager,
$catalogProductFlatState,
$scopeConfig,
$productOptionFactory,
$catalogUrl,
$localeDate,
$customerSession,
$dateTime,
$groupManagement,
$connection
);
$this->temporaryStorageFactory = $temporaryStorageFactory;
$this->searchRequestName = $searchRequestName;
$this->_scopeConfig = $scopeConfig;
$this->_productMetadata = $productMetadata;
$this->_isMTwoOneVersion();
}
/**
* WeltPixel LayeredNavigation Clone collection
*
* @return \WeltPixel\LayeredNavigation\Model\ResourceModel\Fulltext\Collection|null
*/
public function getCollectionClone()
{
if ($this->collectionClone === null) {
$this->collectionClone = clone $this;
$this->collectionClone->setSearchCriteriaBuilder($this->searchCriteriaBuilder->cloneObject());
}
$searchCriterialBuilder = $this->collectionClone->getSearchCriteriaBuilder()->cloneObject();
/** @var \WeltPixel\LayeredNavigation\Model\ResourceModel\Fulltext\Collection $collectionClone */
$collectionClone = clone $this->collectionClone;
$collectionClone->setSearchCriteriaBuilder($searchCriterialBuilder);
return $collectionClone;
}
/**
* WeltPixel LayeredNavigation Add multi-filter categories
*
* @param $categories
* @return $this
*/
public function addLayerCategoryFilter($categories)
{
$this->addFieldToFilter('category_ids', implode(',', $categories));
return $this;
}
/**
* WeltPixel LayeredNavigation remove filter to load option item data
*
* @param $attributeCode
* @return $this
*/
public function removeAttributeSearch($attributeCode)
{
if (is_array($attributeCode)) {
foreach ($attributeCode as $attCode) {
$this->searchCriteriaBuilder->removeFilter($attCode);
}
} else {
$this->searchCriteriaBuilder->removeFilter($attributeCode);
}
$this->_isFiltersRendered = false;
return $this->loadWithFilter();
}
/**
* WeltPixel LayeredNavigation Get attribute condition sql
*
* @param $attribute
* @param $condition
* @param string $joinType
* @return string
*/
public function getAttributeConditionSql($attribute, $condition, $joinType = 'inner')
{
return $this->_getAttributeConditionSql($attribute, $condition, $joinType);
}
/**
* WeltPixel LayeredNavigation Reset Total records
*
* @return $this
*/
public function resetTotalRecords($collectionCount = null)
{
$this->_totalRecords = $collectionCount;
return $this;
}
/**
* @return int|void
*/
public function getSize() {
return sizeof($this->getAllIds());
}
/**
* @return \Magento\Search\Api\SearchInterface|mixed
*/
private function getSearch()
{
if ($this->search === null) {
$this->search = ObjectManager::getInstance()->get('\Magento\Search\Api\SearchInterface');
}
return $this->search;
}
/**
* @param \Magento\Search\Api\SearchInterface $object
*/
public function setSearch(\Magento\Search\Api\SearchInterface $object)
{
$this->search = $object;
}
/**
* @return mixed|\WeltPixel\LayeredNavigation\Model\ResourceModel\Search\SearchCriteriaBuilder
*/
public function getSearchCriteriaBuilder()
{
if ($this->searchCriteriaBuilder === null) {
$this->searchCriteriaBuilder = ObjectManager::getInstance()
->get('\WeltPixel\LayeredNavigation\Model\ResourceModel\Search\SearchCriteriaBuilder');
}
return $this->searchCriteriaBuilder;
}
/**
* @param \WeltPixel\LayeredNavigation\Model\ResourceModel\Search\SearchCriteriaBuilder $object
*/
public function setSearchCriteriaBuilder(\WeltPixel\LayeredNavigation\Model\ResourceModel\Search\SearchCriteriaBuilder $object)
{
$this->searchCriteriaBuilder = $object;
}
/**
* @return \Magento\Framework\Api\FilterBuilder|mixed
*/
private function getFilterBuilder()
{
if ($this->filterBuilder === null) {
$this->filterBuilder = ObjectManager::getInstance()->get('\Magento\Framework\Api\FilterBuilder');
}
return $this->filterBuilder;
}
/**
* @param \Magento\Framework\Api\FilterBuilder $object
*/
public function setFilterBuilder(\Magento\Framework\Api\FilterBuilder $object)
{
$this->filterBuilder = $object;
}
/**
* Apply attribute filter to facet collection
*
* @param string $field
* @param null $condition
* @return $this
*/
public function addFieldToFilter($field, $condition = null)
{
if ($this->searchResult !== null) {
throw new \RuntimeException('Illegal state');
}
$this->getSearchCriteriaBuilder();
$this->getFilterBuilder();
if (is_array($condition) && $this->_isElasticOrOpenSearchEngine()) {
$this->filterBuilder->setField($field);
$this->filterBuilder->setValue($condition);
$this->searchCriteriaBuilder->addFilter($this->filterBuilder->create());
} elseif (!is_array($condition) || !in_array(key($condition), ['from', 'to'])) {
$this->filterBuilder->setField($field);
$this->filterBuilder->setValue($condition);
$this->searchCriteriaBuilder->addFilter($this->filterBuilder->create());
} else {
if (!empty($condition['from'])) {
$this->filterBuilder->setField("{$field}.from");
$this->filterBuilder->setValue($condition['from']);
$this->searchCriteriaBuilder->addFilter($this->filterBuilder->create());
}
if (!empty($condition['to'])) {
$this->filterBuilder->setField("{$field}.to");
$this->filterBuilder->setValue($condition['to']);
$this->searchCriteriaBuilder->addFilter($this->filterBuilder->create());
}
}
return $this;
}
/**
* Add search query filter
*
* @param string $query
* @return $this
*/
public function addSearchFilter($query)
{
$this->queryText = trim($this->queryText . ' ' . $query);
return $this;
}
/**
* @inheritdoc
*/
protected function _renderFiltersBefore()
{
$this->getCollectionClone();
$this->getSearchCriteriaBuilder();
$this->getFilterBuilder();
$this->getSearch();
if ($this->queryText) {
$this->filterBuilder->setField('search_term');
$this->filterBuilder->setValue($this->queryText);
$this->searchCriteriaBuilder->addFilter($this->filterBuilder->create());
}
$priceRangeCalculation = $this->_scopeConfig->getValue(
\Magento\Catalog\Model\Layer\Filter\Dynamic\AlgorithmFactory::XML_PATH_RANGE_CALCULATION,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
if ($priceRangeCalculation) {
$this->filterBuilder->setField('price_dynamic_algorithm');
$this->filterBuilder->setValue($priceRangeCalculation);
$this->searchCriteriaBuilder->addFilter($this->filterBuilder->create());
}
if ($this->_isTwoOne) {
$this->filterBuilder->setField('category_ids');
$this->filterBuilder->setValue($this->_categoryId);
$this->searchCriteriaBuilder->addFilter($this->filterBuilder->create());
}
$searchCriteria = $this->searchCriteriaBuilder->create();
$searchCriteria->setRequestName($this->searchRequestName);
if ($this->_isElasticOrOpenSearchEngine()) {
if ($this->order && isset($this->order['field'])) {
$fieldValue = explode("~", $this->order['field']);
} else {
$fieldValue = [];
$fieldValue[0]=null;
}
if (!$fieldValue[0]) {
$searchCriteria->setSortOrders([
'entity_id' => 'DESC'
]);
} else {
$searchCriteria->setSortOrders([
$fieldValue[0] => $this->order['dir']
]);
}
}
try {
$this->searchResult = $this->getSearch()->search($searchCriteria);
} catch (EmptyRequestDataException $e) {
/** @var \Magento\Framework\Api\Search\SearchResultInterface $searchResult */
$this->searchResult = $this->searchResultFactory->create()->setItems([]);
} catch (\Exception $e) {
throw new LocalizedException(__('Something went wrong, check and test your Search Engine configurations, reindex catalog and clear cache. Thrown error: %1', $e->getMessage()));
}
try {
$temporaryStorage = $this->temporaryStorageFactory->create();
$table = $temporaryStorage->storeDocuments($this->searchResult->getItems());
$this->getSelect()->joinInner(
[
'search_result' => $table->getName(),
],
'e.entity_id = search_result.' . TemporaryStorage::FIELD_ENTITY_ID,
[]
);
if ($this->order && 'relevance' === $this->order['field']) {
$this->getSelect()->order('search_result.' . TemporaryStorage::FIELD_SCORE . ' ' . $this->order['dir']);
}
} catch (\Exception $ex) {
$this->_logger->error($ex->getMessage());
}
parent::_renderFiltersBefore();
}
/**
* @return $this
*/
protected function _renderFilters()
{
$this->_filters = [];
return parent::_renderFilters();
}
/**
* Set Order field
*
* @param string $attribute
* @param string $dir
* @return $this
*/
public function setOrder($attribute, $dir = Select::SQL_DESC)
{
$this->order = ['field' => $attribute, 'dir' => $dir];
if ($attribute != 'relevance') {
parent::setOrder($attribute, $dir);
}
return $this;
}
/**
* Stub method for compatibility with other search engines
*
* @return $this
*/
public function setGeneralDefaultQuery()
{
return $this;
}
/**
* Return field faceted data from faceted search result
*
* @param string $field
* @return array
* @throws StateException
*/
public function getFacetedData($field)
{
$this->_renderFilters();
$result = [];
$aggregations = $this->searchResult->getAggregations();
if (null !== $aggregations) {
$bucket = $aggregations->getBucket($field . RequestGenerator::BUCKET_SUFFIX);
if ($bucket) {
foreach ($bucket->getValues() as $value) {
$metrics = $value->getMetrics();
$result[$metrics['value']] = $metrics;
}
} else {
throw new StateException(__('Bucket does not exist'));
}
}
return $result;
}
/**
* Specify category filter for product collection
*
* @param \Magento\Catalog\Model\Category $category
* @return $this
*/
public function addCategoryFilter(\Magento\Catalog\Model\Category $category)
{
$this->_categoryId = $category->getId();
$this->addFieldToFilter('category_ids', $category->getId());
return parent::addCategoryFilter($category);
}
/**
* Set product visibility filter for enabled products
*
* @param array $visibility
* @return $this
*/
public function setVisibility($visibility)
{
$this->addFieldToFilter('visibility', $visibility);
return parent::setVisibility($visibility);
}
/**
* Check the engine provider is 'elasticsearch'
* @deprecated
*
* @return bool
*/
protected function _isElasticSearchEngine()
{
$currentEngine = $this->_scopeConfig->getValue(EngineInterface::CONFIG_ENGINE_PATH, ScopeInterface::SCOPE_STORE);
if ($currentEngine == 'elasticsearch' || $currentEngine == 'elasticsearch5' || $currentEngine == 'elasticsearch6'
|| $currentEngine == 'elasticsearch7' || $currentEngine == 'elasticsearch8') {
return true;
}
return false;
}
/**
* Check the engine provider is 'elasticsearch' or 'opensearch'
*
* @return bool
*/
protected function _isElasticOrOpenSearchEngine()
{
$currentEngine = $this->_scopeConfig->getValue(EngineInterface::CONFIG_ENGINE_PATH, ScopeInterface::SCOPE_STORE);
if ($currentEngine == 'elasticsearch' || $currentEngine == 'elasticsearch5' || $currentEngine == 'elasticsearch6'
|| $currentEngine == 'elasticsearch7' || $currentEngine == 'opensearch') {
return true;
}
return false;
}
/**
* check magento version
* @return bool
*/
protected function _isMTwoOneVersion()
{
$version = $this->_productMetadata->getVersion();
$pos = strpos($version, '2.1');
if ($pos === false) {
$this->_isTwoOne = false;
} else {
$this->_isTwoOne = true;
}
return $this->_isTwoOne;
}
}
@@ -0,0 +1,61 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\ResourceModel\Layer\Filter;
/**
* Class Attribute
* @package WeltPixel\LayeredNavigation\Model\ResourceModel\Layer\Filter
*/
class Attribute extends \Magento\Catalog\Model\ResourceModel\Layer\Filter\Attribute
{
/**
* Retrieve array with products counts per attribute option
*
* @param \Magento\Catalog\Model\Layer\Filter\FilterInterface $filter
* @throws \Magento\Framework\Exception\LocalizedException
* @return array
*/
public function getCount(\Magento\Catalog\Model\Layer\Filter\FilterInterface $filter)
{
// clone select from collection with filters
$layer = $filter->getLayer();
if($layer instanceof \Magento\Catalog\Model\Layer\Search) {
$collectionSelect = $layer->getProductCollection()->getSelect();
} else {
$collectionSelect = $layer->getCurrentCategory()->getProductCollection()->getSelect();
}
$select = clone $collectionSelect;
// reset columns, order and limitation conditions
$select->reset(\Magento\Framework\DB\Select::COLUMNS);
$select->reset(\Magento\Framework\DB\Select::ORDER);
$select->reset(\Magento\Framework\DB\Select::LIMIT_COUNT);
$select->reset(\Magento\Framework\DB\Select::LIMIT_OFFSET);
$connection = $this->getConnection();
$attribute = $filter->getAttributeModel();
$tableAlias = sprintf('%s_idx', $attribute->getAttributeCode());
$conditions = [
"{$tableAlias}.entity_id = e.entity_id",
$connection->quoteInto("{$tableAlias}.attribute_id = ?", $attribute->getAttributeId()),
$connection->quoteInto("{$tableAlias}.store_id = ?", $filter->getStoreId()),
];
$select->join(
[$tableAlias => $this->getMainTable()],
join(' AND ', $conditions),
['value', 'count' => new \Zend_Db_Expr("COUNT({$tableAlias}.entity_id)")]
)->group(
"{$tableAlias}.value"
);
return $connection->fetchPairs($select);
}
}
@@ -0,0 +1,19 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\ResourceModel\Search;
use Magento\Framework\Api\Search\FilterGroup as SourceFilterGroup;
/**
* Class FilterGroup
* @package WeltPixel\LayeredNavigation\Model\ResourceModel\Search
*/
class FilterGroup extends SourceFilterGroup
{
}
@@ -0,0 +1,92 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\ResourceModel\Search;
use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\ObjectFactory;
use Magento\Framework\Api\Search\FilterGroup as SourceFilterGroup;
use Magento\Framework\Api\Search\FilterGroupBuilder as SourceFilterGroupBuilder;
use Magento\Framework\App\RequestInterface;
/**
* Class FilterGroupBuilder
* @package WeltPixel\LayeredNavigation\Model\ResourceModel\Search
*/
class FilterGroupBuilder extends SourceFilterGroupBuilder
{
/** @var \Magento\Framework\App\RequestInterface */
protected $_request;
/**
* FilterGroupBuilder constructor.
* @param \Magento\Framework\Api\ObjectFactory $objectFactory
* @param \Magento\Framework\Api\FilterBuilder $filterBuilder
* @param \Magento\Framework\App\RequestInterface $request
*/
public function __construct(
ObjectFactory $objectFactory,
FilterBuilder $filterBuilder,
RequestInterface $request
)
{
parent::__construct($objectFactory, $filterBuilder);
$this->_request = $request;
}
/**
* @return FilterGroupBuilder
*/
public function cloneObject()
{
$cloneObject = clone $this;
$cloneObject->setFilterBuilder(clone $this->_filterBuilder);
return $cloneObject;
}
/**
* @param $filterBuilder
*/
public function setFilterBuilder($filterBuilder)
{
$this->_filterBuilder = $filterBuilder;
}
/**
* @param $attributeCode
*
* @return $this
*/
public function removeFilter($attributeCode)
{
if (isset($this->data[SourceFilterGroup::FILTERS])) {
foreach ($this->data[SourceFilterGroup::FILTERS] as $key => $filter) {
if ($filter->getField() == $attributeCode) {
if (($attributeCode == 'category_ids') && ($filter->getValue() == $this->_request->getParam('id'))) {
continue;
}
unset($this->data[SourceFilterGroup::FILTERS][$key]);
}
}
}
return $this;
}
/**
* Return the Data type class name
*
* @return string
*/
protected function _getDataObjectType()
{
return 'Magento\Framework\Api\Search\FilterGroup';
}
}
@@ -0,0 +1,19 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\ResourceModel\Search;
use Magento\Framework\Api\Search\SearchCriteria as SourceSearchCriteria;
/**
* Class SearchCriteria
* @package WeltPixel\LayeredNavigation\Model\ResourceModel\Search
*/
class SearchCriteria extends SourceSearchCriteria
{
}
@@ -0,0 +1,73 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\ResourceModel\Search;
use Magento\Framework\Api\ObjectFactory;
use Magento\Framework\Api\Search\SearchCriteriaBuilder as SourceSearchCriteriaBuilder;
use Magento\Framework\Api\SortOrderBuilder;
/**
* Class SearchCriteriaBuilder
* @package WeltPixel\LayeredNavigation\Model\ResourceModel\Search
*/
class SearchCriteriaBuilder extends SourceSearchCriteriaBuilder
{
/**
* @param ObjectFactory $objectFactory
* @param FilterGroupBuilder $filterGroupBuilder
* @param SortOrderBuilder $sortOrderBuilder
*/
public function __construct(
ObjectFactory $objectFactory,
FilterGroupBuilder $filterGroupBuilder,
SortOrderBuilder $sortOrderBuilder
)
{
parent::__construct($objectFactory, $filterGroupBuilder, $sortOrderBuilder);
}
/**
* @param $attributeCode
*
* @return $this
*/
public function removeFilter($attributeCode)
{
$this->filterGroupBuilder->removeFilter($attributeCode);
return $this;
}
/**
* @return SearchCriteriaBuilder
*/
public function cloneObject()
{
$cloneObject = clone $this;
$cloneObject->setFilterGroupBuilder($this->filterGroupBuilder->cloneObject());
return $cloneObject;
}
/**
* @param $filterGroupBuilder
*/
public function setFilterGroupBuilder($filterGroupBuilder)
{
$this->filterGroupBuilder = $filterGroupBuilder;
}
/**
* @return string
*/
protected function _getDataObjectType()
{
return 'Magento\Framework\Api\Search\SearchCriteria';
}
}
@@ -0,0 +1,803 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Observer\Edit\Tab\Front;
use Magento\Config\Model\Config\Source;
use Magento\Framework\Module\Manager;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Request\Http;
use WeltPixel\LayeredNavigation\Model\AttributeOptions;
use Magento\Catalog\Model\ResourceModel\Eav\Attribute;
use Magento\Catalog\Helper\Category;
/**
* Class WpProductAttributeFormBuildFrontTabObserver
* @package WeltPixel\LayeredNavigation\Observer\Edit\Tab\Front
*/
class WpProductAttributeFormBuildFrontTabObserver implements ObserverInterface
{
/**
* @var \Magento\Config\Model\Config\Source\Yesno
*/
protected $optionList;
/**
* @var \Magento\Framework\Module\Manager
*/
protected $moduleManager;
/**
* @var Http
*/
protected $_request;
/**
* @var AttributeOptions
*/
protected $_wpModel;
protected $_wpAttributeObj = false;
/**
* @var Attribute
*/
protected $_attributeModel;
/**
* @var \Magento\Catalog\Block\Adminhtml\Category\Tree
*/
protected $adminCategoryTree;
/**
* @var \Magento\Catalog\Model\Indexer\Category\Flat\State
*/
protected $categoryFlatConfig;
/**
* WpProductAttributeFormBuildFrontTabObserver constructor.
* @param Manager $moduleManager
* @param Source\Yesno $optionList
* @param Http $request
* @param AttributeOptions $wpModel
* @param Attribute $attributeModel
* @param \Magento\Catalog\Model\Indexer\Category\Flat\State $categoryFlatState
* @param \Magento\Catalog\Block\Adminhtml\Category\Tree $adminCategoryTree
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function __construct(
Manager $moduleManager,
Source\Yesno $optionList,
Http $request,
AttributeOptions $wpModel,
Attribute $attributeModel,
\Magento\Catalog\Model\Indexer\Category\Flat\State $categoryFlatState,
\Magento\Catalog\Block\Adminhtml\Category\Tree $adminCategoryTree
)
{
$this->optionList = $optionList;
$this->moduleManager = $moduleManager;
$this->_request = $request;
$this->_wpModel = $wpModel;
$this->_attributeModel = $attributeModel;
$this->categoryFlatConfig = $categoryFlatState;
$this->adminCategoryTree = $adminCategoryTree;
$this->_getWpAttributeOptionValues();
}
/**
* @param \Magento\Framework\Event\Observer $observer
* @return void
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
if (!$this->moduleManager->isOutputEnabled('WeltPixel_LayeredNavigation')) {
return;
}
$isSwatchAttr = $this->_isSwatchAttr();
$swatchComment = $isSwatchAttr ? '<br/>This setting can not be used with swatch attribute types.' : '';
/** @var \Magento\Framework\Data\Form\AbstractForm $form */
$form = $observer->getForm();
$fieldset = $form->addFieldset(
'wp_front_fieldset',
['legend' => __('WeltPixel Layered Navigation Properties'), 'collapsable' => false]
);
$field = '';
if(!$isSwatchAttr) {
$value = [
['value' => 0, 'label' => __('Closed')],
['value' => 1, 'label' => __('Fully Opened')],
['value' => 2, 'label' => __('Expandable')],
];
} else {
$value = [
['value' => 0, 'label' => __('Closed')],
['value' => 1, 'label' => __('Fully Opened')],
];
}
$fieldset->addField(
'wp_display_options',
'select',
[
'name' => 'wp_display_options',
'label' => __("Show Attribute Options as"),
'title' => __('Can be used only with catalog input type Dropdown, Multiple Select and Price'),
'note' => __('[Closed] option not applicable on [Slide Down] Sidebar Style. <br/> The [Closed] option is recommended if you’re using the Horizontal Design for the Layered Navigation'),
'values' => $value,
'value' => $this->_getDisplayOption(),
]
);
$field = $fieldset->addField(
'wp_visible_options',
'text',
[
'name' => 'wp_visible_options',
'label' => __("Initial Number of Visible Options"),
'value' => $this->_getVisibleOptions(),
'title' => __('The number of attribute option(s) that will be initially visible. Can be used only with Show Attribute Options as - Expandable.'),
'note' => __('The number of attribute option(s) that will be initially visible. Can be used only with Show Attribute Options as - Expandable. %1', $swatchComment)
]
);
$field = $fieldset->addField(
'wp_visible_options_step',
'select',
[
'name' => 'wp_visible_options_step',
'label' => __("Expandable items behaviour"),
'values' => [
['value' => 99, 'label' => __('All')],
['value' => 5, 'label' => __('Show 5 more')],
['value' => 10, 'label' => __('Show 10 more')],
['value' => 15, 'label' => __('Show 15 more')],
],
'value' => $this->_getVisibleOptions(),
'title' => __('Select the number of attribute option(s) to show/hide when using Expand feature.<br> Can be used only with Show Attribute Options as - Expandable.'),
'note' => __('Select the number of attribute option(s) to show/hide when using Expand feature.<br> Can be used only with Show Attribute Options as - Expandable. %1', $swatchComment)
]
);
$fieldset->addField(
'wp_is_multiselect',
'select',
[
'name' => 'wp_is_multiselect',
'label' => __("Enable Multiselect"),
'value' => $this->_getIsMultiselect(),
'values' => [
['value' => 0, 'label' => __('No')],
['value' => 1, 'label' => __('Yes')],
],
'title' => __('Allow to filter multiple options from the same attribute.'),
'note' => __('Allow to filter multiple options from the same attribute.')
]
);
$fieldset->addField(
'wp_keep_open_after_filter',
'select',
[
'name' => 'wp_keep_open_after_filter',
'label' => __("Keep attribute opened after filterings"),
'value' => $this->_getKeepOpenAfterFilter(),
'values' => [
['value' => 0, 'label' => __('No')],
['value' => 1, 'label' => __('Yes')],
],
'title' => __('Allow to keep attribute open after filtering.'),
'note' => __('Allow to keep attribute open after filtering.')
]
);
$fieldset->addField(
'wp_show_quantity',
'select',
[
'name' => 'wp_show_quantity',
'label' => __("Show Item Counter"),
'value' => $this->_getShowQuantity(),
'values' => [
['value' => 0, 'label' => __('No')],
['value' => 1, 'label' => __('Yes')],
],
'title' => __('Show item counter next to the current attribute options.'),
'note' => __('Show item counter next to the current attribute options. %1', $swatchComment)
]
);
$fieldset->addField(
'wp_sort_by',
'select',
[
'name' => 'wp_sort_by',
'label' => __("Sort By"),
'value' => $this->_getSortBy(),
'values' => [
['value' => 1, 'label' => __('Position')],
['value' => 2, 'label' => __('Name')],
],
'title' => __('Select the sorting of the current attribute options.'),
'note' => __('Select the sorting of the current attribute options. %1', $swatchComment)
]
);
if(!$isSwatchAttr) {
$fieldset->addField(
'wp_instant_search',
'select',
[
'name' => 'wp_instant_search',
'label' => __("Enable options filter on Desktop"),
'value' => $this->_getInstantSearch(),
'values' => [
['value' => 0, 'label' => __('No')],
['value' => 1, 'label' => __('Yes')],
],
'title' => __('Enable search functionality for attribute options on desktop.'),
'note' => __('Enable search functionality for attribute options on desktop. %1', $swatchComment)
]
);
$fieldset->addField(
'wp_instant_search_mobile',
'select',
[
'name' => 'wp_instant_search_mobile',
'label' => __("Enable options filter on Mobile"),
'value' => $this->_getInstantSearchMobile(),
'values' => [
['value' => 0, 'label' => __('No')],
['value' => 1, 'label' => __('Yes')],
],
'title' => __('Enable search functionality for attribute options on mobile.'),
'note' => __('Enable search functionality for attribute options on mobile. %1', $swatchComment)
]
);
}
$fieldset->addField(
'wp_category_visibility',
'select',
[
'name' => 'wp_category_visibility',
'label' => __("Category Visibility"),
'value' => $this->_getCategoryVisibility(),
'values' => [
['value' => 0, 'label' => __('Visible in all categories')],
['value' => 1, 'label' => __('Visible only in the following categories')],
['value' => 2, 'label' => __('Not visible in the following categories')],
],
'title' => __('Select visibility behaviour in categories for the current attribute.'),
'note' => __('Select visibility behaviour in categories for the current attribute.')
]
);
$fieldset->addField(
'wp_category_ids',
'multiselect',
[
'name' => 'wp_category_ids[]',
'label' => __("Select Categories"),
'value' => $this->_getCategoryIds(),
'values' => $this->categoriesToOptionArray(),
'title' => __('Select categories.'),
'note' => __('Select categories.')
]
);
if ($field) {
$field->setAfterElementHtml(
"<script>
//<![CDATA[
require(['jquery', 'jquery/ui'], function($){
var acceptedTypeArray = ['select','multiselect','price','swatch_visual','swatch_text'],
wpDisplayOptionEl = $('#wp_display_options'),
wpVisibleOptionsEl = $('#wp_visible_options'),
wpVisibleOptionsStepEl = $('#wp_visible_options_step'),
wpIsMultiselectEl = $('#wp_is_multiselect'),
wpKeepAttributeOpenEl = $('#wp_keep_open_after_filter'),
wpKeepAttributeOpenRow = $('.field-wp_keep_open_after_filter'),
wpShowQuantityEl = $('#wp_show_quantity'),
wpSortByEl = $('#wp_sort_by'),
wpIsD = $('#wp_instant_search'),
wpIsM = $('#wp_instant_search_mobile'),
mageFrontendInpEl = $('#frontend_input'),
categoryVisibilityEl = $('#wp_category_visibility'),
categoryIdsElement = $('#wp_category_ids'),
categoryIdsEl = $('.field-wp_category_ids'),
displayOpt = '" . $this->_getDisplayOption() . "',
visibleOpt = '" . $this->_getVisibleOptions() . "',
visibleOptStep = '" . $this->_getVisibleOptionsStep() . "',
isMultiselect = '" . $this->_getIsMultiselect() . "',
isAttributeOpen = '" . $this->_getKeepOpenAfterFilter() . "',
showQuantity = '" . $this->_getShowQuantity() . "',
sortBy = '" . $this->_getSortBy() . "';
instantSearchD = '" . $this->_getInstantSearch() . "';
instantSearchM = '" . $this->_getInstantSearchMobile() . "';
categoryVisibility = '".$this->_getCategoryVisibility()."';
categoryIds = '".$this->_getCategoryIds()."';
categoryIdsArray = categoryIds.split(',');
isSwatch = '".$isSwatchAttr."';
wpDisplayOptionEl.val(displayOpt);
wpVisibleOptionsEl.val(visibleOpt);
wpVisibleOptionsStepEl.val(visibleOptStep);
wpIsMultiselectEl.val(isMultiselect);
wpKeepAttributeOpenEl.val(isAttributeOpen);
wpShowQuantityEl.val(showQuantity);
wpSortByEl.val(sortBy);
wpIsD.val(instantSearchD);
wpIsM.val(instantSearchM);
categoryVisibilityEl.val(categoryVisibility);
categoryIdsElement.val(categoryIdsArray);
setWpVisibility();
wpIsMultiselectEl.change(function() {
if(wpIsMultiselectEl.val() != 0) {
wpKeepAttributeOpenRow.show();
} else {
wpKeepAttributeOpenRow.hide();
}
});
categoryVisibilityEl.change(function() {
if(categoryVisibilityEl.val() != 0) {
categoryIdsEl.show();
} else {
categoryIdsEl.hide();
}
})
wpDisplayOptionEl.change(function(){
if($(this).val() == 2) {
enableElement(wpVisibleOptionsEl);
enableElement(wpVisibleOptionsStepEl);
wpVisibleOptionsEl.val(visibleOpt);
wpVisibleOptionsStepEl.val(visibleOptStep);
} else {
wpVisibleOptionsEl.val(99);
wpVisibleOptionsStepEl.val(99);
disableElement(wpVisibleOptionsEl);
disableElement(wpVisibleOptionsStepEl);
}
});
mageFrontendInpEl.change(function(){
var selVal = $(this).val();
if($.inArray(selVal, acceptedTypeArray) !== -1) {
enableElement(wpDisplayOptionEl);
enableElement(wpIsMultiselectEl);
enableElement(wpShowQuantityEl);
enableElement(wpSortByEl);
if(wpDisplayOptionEl.val() == 2){
enableElement(wpVisibleOptionsEl);
enableElement(wpVisibleOptionsStepEl);
} else {
disableElement(wpVisibleOptionsEl);
disableElement(wpVisibleOptionsStepEl);
}
} else {
disableElement(wpVisibleOptionsEl);
disableElement(wpVisibleOptionsStepEl);
disableElement(wpDisplayOptionEl);
disableElement(wpIsMultiselectEl);
disableElement(wpShowQuantityEl);
disableElement(wpSortByEl);
}
});
/**
* set wp fields property(disabled)
*/
function setWpVisibility(){
var elVal = mageFrontendInpEl.val();
if(categoryVisibilityEl.val() != 0) {
categoryIdsEl.show();
} else {
categoryIdsEl.hide();
}
if(wpIsMultiselectEl.val() != 0) {
wpKeepAttributeOpenRow.show();
} else {
wpKeepAttributeOpenRow.hide();
}
if($.inArray(elVal, acceptedTypeArray) !== -1) {
enableElement(wpDisplayOptionEl);
enableElement(wpIsMultiselectEl);
enableElement(wpShowQuantityEl);
enableElement(wpSortByEl);
} else {
disableElement(wpVisibleOptionsEl);
disableElement(wpVisibleOptionsStepEl);
disableElement(wpDisplayOptionEl);
disableElement(wpIsMultiselectEl);
disableElement(wpShowQuantityEl);
disableElement(wpSortByEl);
}
if(wpDisplayOptionEl.val() != 2){
disableElement(wpVisibleOptionsEl);
disableElement(wpVisibleOptionsStepEl);
}
if(isSwatch) {
disableElement(wpVisibleOptionsEl);
disableElement(wpVisibleOptionsStepEl);
disableElement(wpShowQuantityEl);
disableElement(wpSortByEl);
disableElement(wpIsD);
disableElement(wpIsM);
disableElement(wpIsM);
}
}
/**
* set element as disabled
* @param element
*/
function disableElement(element) {
element.prop('disabled', true);
}
/**
* remove 'disabled' attribute from element
* @param element
*/
function enableElement(element) {
element.removeAttr('disabled');
}
});
//]]>
</script>"
);
}
}
protected function _isSwatchAttr() {
$attributeId = $this->_request->getParam('attribute_id');
if ($attributeId) {
$attr = $this->_attributeModel->load($attributeId);
if(!$attr->getAdditionalData()) {
return false;
}
$addititonalData = $attr->getAdditionalData();
$attrData = json_decode($addititonalData, true);
if(isset($attrData['swatch_input_type'])) {
return true;
}
return true;
}
return false;
}
/**
* Check if value is a serialized string
*
* @param string $value
* @return boolean
*/
private function isSerialized($value)
{
return (boolean) preg_match('/^((s|i|d|b|a|O|C):|N;)/', $value);
}
/**
* @return $this|bool
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function _getWpAttributeOptionValues()
{
$attributeId = $this->_request->getParam('attribute_id');
if ($attributeId) {
$this->_wpAttributeObj = $this->_wpModel->getDisplayOptionsByAttribute($attributeId);
}
return $this;
}
/**
* Get attribute 'display_option' value
* @return int
*/
protected function _getDisplayOption()
{
$val = AttributeOptions::DISPLAY_OPTION_DEF_VAL;
if($this->_wpAttributeObj) {
if(!empty($this->_wpAttributeObj->getData())) {
$val = $this->_wpAttributeObj->getDisplayOption();
}
}
return $val;
}
/**
* Get attribute 'visible_options' value
* @return int
*/
protected function _getVisibleOptions()
{
$val = '';
if($this->_wpAttributeObj) {
if(!empty($this->_wpAttributeObj->getData())) {
$val = $this->_wpAttributeObj->getVisibleOptions();
}
}
return $val;
}
/**
* Get attribute 'visible_options' value
* @return int
*/
protected function _getVisibleOptionsStep()
{
$val = '';
if($this->_wpAttributeObj) {
if(!empty($this->_wpAttributeObj->getData())) {
$val = $this->_wpAttributeObj->getVisibleOptionsStep();
}
}
return $val;
}
/**
* Get attribute 'is_multiselect' value
* @return int
*/
protected function _getIsMultiselect()
{
$val = 0;
if($this->_wpAttributeObj) {
if(!empty($this->_wpAttributeObj->getData())) {
$val = $this->_wpAttributeObj->getIsMultiselect();
}
}
return $val;
}
/**
* Get attribute 'keep_open_after_filter' value
* @return int
*/
protected function _getKeepOpenAfterFilter()
{
$val = 0;
if($this->_wpAttributeObj) {
if(!empty($this->_wpAttributeObj->getData())) {
$val = $this->_wpAttributeObj->getKeepOpenAfterFilter();
}
}
return $val;
}
/**
* Get attribute 'show_quantity' value
* @return int
*/
protected function _getShowQuantity()
{
$val = 0;
if($this->_wpAttributeObj) {
if(!empty($this->_wpAttributeObj->getData())) {
$val = $this->_wpAttributeObj->getShowQuantity();
}
}
return $val;
}
/**
* Get attribute 'sort_by' value
* @return int
*/
protected function _getSortBy()
{
$val = 1;
if($this->_wpAttributeObj) {
if(!empty($this->_wpAttributeObj->getData())) {
$val = $this->_wpAttributeObj->getSortBy();
}
}
return $val;
}
/**
* Get attribute 'instant_search' value
* @return int
*/
protected function _getInstantSearch()
{
$val = 0;
if($this->_wpAttributeObj) {
if(!empty($this->_wpAttributeObj->getData())) {
$val = $this->_wpAttributeObj->getInstantSearch();
}
}
return $val;
}
/**
* Get attribute 'instant_search_mobile' value
* @return int
*/
protected function _getInstantSearchMobile()
{
$val = 0;
if($this->_wpAttributeObj) {
if(!empty($this->_wpAttributeObj->getData())) {
$val = $this->_wpAttributeObj->getInstantSearchMobile();
}
}
return $val;
}
/**
* Get attribute 'category_visibility' value
* @return int
*/
protected function _getCategoryVisibility()
{
$val = 0;
if($this->_wpAttributeObj) {
if(!empty($this->_wpAttributeObj->getData())) {
$val = $this->_wpAttributeObj->getCategoryVisibility();
}
}
return $val;
}
/**
* Get attribute 'category_visibility' value
* @return int
*/
protected function _getCategoryIds()
{
$val = 0;
if($this->_wpAttributeObj) {
if(!empty($this->_wpAttributeObj->getData())) {
$val = $this->_wpAttributeObj->getCategoryIds();
}
}
return $val;
}
/**
* @param array $result
* @param string $prefix
* @param array $category
* @param bool $ignore
*/
protected function recursiveCategories(&$result, $prefix, $category, $ignore = false)
{
if (!$ignore) {
$result[$prefix . $category['id']] = __($category['text']);
$prefix = $prefix . $category['id'] . '_';
}
if (isset($category['children'])) {
foreach ($category['children'] as $categ) {
$this->recursiveCategories($result, $prefix, $categ);
}
}
}
/**
* Get options in "key-value" format
* @return array
*/
public function categoriesArray()
{
$categories = $this->adminCategoryTree->getTree();
$categoryList = [];
foreach ($categories as $category) {
$this->recursiveCategories($categoryList, '', $category, true);
}
return $categoryList;
}
/**
* @return array
*/
public function categoriesToOptionArray()
{
$arr = $this->categoriesArray();
$ret = [];
foreach ($arr as $key => $value)
{
$catIdArr = explode('_', $key);
if(count($catIdArr) == 1) {
$ret[] = [
'value' => $key,
'label' => $value,
'style' => 'font-weight:bold'
];
} elseif(count($catIdArr) == 2) {
$ret[] = [
'value' => $catIdArr[1],
'label' => $value,
'style' => 'padding-left: 25px'
];
} elseif(count($catIdArr) == 3) {
$ret[] = [
'value' => $catIdArr[2],
'label' => $value,
'style' => 'padding-left: 45px'
];
} else {
$ret[] = [
'value' => $catIdArr[3],
'label' => $value,
'style' => 'padding-left: 65px'
];
}
}
return $ret;
}
/**
* @param $category
* @return array
*/
public function getChildCategories($category)
{
if ($this->categoryFlatConfig->isFlatEnabled() && $category->getUseFlatResource()) {
$subcategories = (array)$category->getChildrenNodes();
} else {
$subcategories = $category->getChildren();
}
return $subcategories;
}
}
@@ -0,0 +1,100 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
/**
* Class RemoveBlocks
* @package WeltPixel\LayeredNavigation\Observer
*/
class RemoveBlocks implements ObserverInterface
{
/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
protected $_scopeConfig;
/**
* @var \WeltPixel\LayeredNavigation\Helper\Data
*/
protected $_wpHelper;
/**
* @var \Magento\Framework\App\Request\Http
*/
protected $_request;
/**
* RemoveBlocks constructor.
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \WeltPixel\LayeredNavigation\Helper\Data $wpHelper
* @param \Magento\Framework\App\Request\Http $request
*/
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\WeltPixel\LayeredNavigation\Helper\Data $wpHelper,
\Magento\Framework\App\Request\Http $request
) {
$this->_scopeConfig = $scopeConfig;
$this->_wpHelper = $wpHelper;
$this->_request = $request;
}
public function execute(Observer $observer)
{
if($this->_isAdvancedSearchResultPage() || !$this->_wpHelper->isEnabled()) {
return;
}
/** @var \Magento\Framework\View\Layout $layout */
$layout = $observer->getLayout();
$wishlistBlock = $layout->getBlock('wishlist_sidebar');
$compareBlock = $layout->getBlock('catalog.compare.sidebar');
$reorderBlock = $layout->getBlock('sale.reorder.sidebar');
$slideMode = $this->_wpHelper->getSlideMode();
if($wishlistBlock) {
$showWishlistBlock = $this->_wpHelper->showWishlistBlock();
if (!$showWishlistBlock || $slideMode) {
$layout->unsetElement('wishlist_sidebar');
}
}
if($compareBlock) {
$showCompareBlock = $this->_wpHelper->showCompareBlock();
if (!$showCompareBlock || $slideMode) {
$layout->unsetElement('catalog.compare.sidebar');
}
}
if ($reorderBlock) {
$showRecentlyOrderedBlock = $this->_wpHelper->showRecentlyOrderedBlock();
if (!$showRecentlyOrderedBlock || $slideMode) {
$layout->unsetElement('sale.reorder.sidebar');
}
}
}
/**
* @return bool
*/
protected function _isAdvancedSearchResultPage() {
$is = false;
$controller = $this->_request->getControllerName();
$action = $this->_request->getActionName();
$route = $this->_request->getRouteName();
if($route == 'catalogsearch' && $controller == 'advanced' && $action == 'result') {
$is = true;
}
return $is;
}
}
@@ -0,0 +1,39 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
/**
* Class UpdateBodyClass
* @package WeltPixel\LayeredNavigation\Observer
*/
class UpdateBodyClass implements ObserverInterface
{
/**
* @var \WeltPixel\LayeredNavigation\Helper\Data
*/
protected $_wpHelper;
/**
* RemoveBlocks constructor.
* @param \WeltPixel\LayeredNavigation\Helper\Data $wpHelper
*/
public function __construct(
\WeltPixel\LayeredNavigation\Helper\Data $wpHelper
) {
$this->_wpHelper = $wpHelper;
}
public function execute(Observer $observer)
{
$this->_wpHelper->updateSliderBodyClass();
}
}
@@ -0,0 +1,95 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Observer;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
/**
* Class WpCatalogAttributeSaveAfterObserver
* @package WeltPixel\LayeredNavigation\Model\Observer
*/
class WpCatalogAttributeSaveAfterObserver implements ObserverInterface
{
/**
* @var array
*/
protected $_lnInputTypes = [
'select',
'multiselect',
'price'
];
/**
* @var \WeltPixel\LayeredNavigation\Model\AttributeOptions
*/
protected $_attributeOptions;
/**
* @param CheckSalesRulesAvailability $checkSalesRulesAvailability
*/
public function __construct(
\WeltPixel\LayeredNavigation\Model\AttributeOptions $attributeOptions
)
{
$this->_attributeOptions = $attributeOptions;
}
/**
* After save attribute
*
* @param EventObserver $observer
* @return $this
*/
public function execute(EventObserver $observer)
{
$attribute = $observer->getEvent()->getAttribute();
$wpAttributeOptions = $this->_attributeOptions->getDisplayOptionsByAttribute($attribute->getAttributeId());
if (in_array($attribute->getFrontendInput(), $this->_lnInputTypes)) {
// insert
if (!$wpAttributeOptions->getId()) {
$categoryIds = (null !== $attribute->getWpCategoryIds() && is_array($attribute->getWpCategoryIds())) ? implode(',',$attribute->getWpCategoryIds()) : '';
$this->_attributeOptions->setAttributeId($attribute->getAttributeId())
->setDisplayOption($attribute->getWpDisplayOptions())
->setVisibleOptions($attribute->getWpVisibleOptions())
->setVisibleOptionsStep($attribute->getWpVisibleOptionsStep())
->setIsMultiselect($attribute->getWpIsMultiselect())
->setKeepOpenAfterFilter($attribute->getWpKeepOpenAfterFilter())
->setShowQuantity($attribute->getWpShowQuantity())
->setSortBy($attribute->getWpSortBy())
->setInstantSearch($attribute->getWpInstantSearch())
->setInstantSearchMobile($attribute->getWpInstantSearchMobile())
->setCategoryVisibility($attribute->getWpCategoryVisibility())
->setCategoryIds($categoryIds)
->save();
} // update
else {
$visibleItems = ($attribute->getWpDisplayOptions() == \WeltPixel\LayeredNavigation\Model\AttributeOptions::DISPLAY_OPTION_OPEN_VAL || $attribute->getWpDisplayOptions() == \WeltPixel\LayeredNavigation\Model\AttributeOptions::DISPLAY_OPTION_DEF_VAL) ? \WeltPixel\LayeredNavigation\Model\AttributeOptions::VISIBLE_OPTIONS_DEF_VAL : $attribute->getWpVisibleOptions();
$visibleItemsStep = (!$attribute->getWpDisplayOptions() == \WeltPixel\LayeredNavigation\Model\AttributeOptions::DISPLAY_OPTION_OPEN_VAL || $attribute->getWpDisplayOptions() == \WeltPixel\LayeredNavigation\Model\AttributeOptions::DISPLAY_OPTION_DEF_VAL) ? \WeltPixel\LayeredNavigation\Model\AttributeOptions::VISIBLE_OPTIONS_STEP_DEF_VAL : $attribute->getWpVisibleOptionsStep();
$categoryIds = (null !== $attribute->getWpCategoryIds() && is_array($attribute->getWpCategoryIds())) ? implode(',',$attribute->getWpCategoryIds()) : '';
$this->_attributeOptions->setId($wpAttributeOptions->getId())
->setDisplayOption($attribute->getWpDisplayOptions())
->setVisibleOptions($visibleItems)
->setVisibleOptionsStep($visibleItemsStep)
->setIsMultiselect($attribute->getWpIsMultiselect())
->setKeepOpenAfterFilter($attribute->getWpKeepOpenAfterFilter())
->setShowQuantity($attribute->getWpShowQuantity())
->setSortBy($attribute->getWpSortBy())
->setInstantSearch($attribute->getWpInstantSearch())
->setInstantSearchMobile($attribute->getWpInstantSearchMobile())
->setCategoryVisibility($attribute->getWpCategoryVisibility())
->setCategoryIds($categoryIds)
->save();
}
}
return $this;
}
}
@@ -0,0 +1,195 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Plugin\CatalogSearch;
use Magento\Catalog\Model\Layer\Resolver;
use Magento\CatalogSearch\Helper\Data as CatalogSearchHelper;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\View\Result\PageFactory;
use Magento\Search\Model\QueryFactory;
use Magento\Store\Model\StoreManagerInterface;
use WeltPixel\LayeredNavigation\Helper\Data as WpHelper;
/**
* Class View
* @package WeltPixel\LayeredNavigation\Plugin\Category
*/
class ResultView
{
/**
* Catalog session
*
* @var Session
*/
protected $_catalogSession;
/**
* @var StoreManagerInterface
*/
protected $_storeManager;
/**
* @var QueryFactory
*/
private $_queryFactory;
/**
* Catalog Layer Resolver
*
* @var Resolver
*/
protected $layerResolver;
/**
* @var JsonFactory
*/
protected $_resultJsonFactory;
/**
* @var PageFactory
*/
protected $_resultPageFactory;
/**
* @var CatalogSearchHelper
*/
protected $_catalogSearchHelper;
/**
* @var WpHelper
*/
protected $_wpHelper;
/**
* ResultView constructor.
* @param StoreManagerInterface $storeManager
* @param QueryFactory $queryFactory
* @param Resolver $layerResolver
* @param JsonFactory $resultJsonFactory
* @param PageFactory $resultPageFactory
* @param CatalogSearchHelper $catalogSearchHelper
* @param WpHelper $wpHelper
*/
public function __construct(
StoreManagerInterface $storeManager,
QueryFactory $queryFactory,
Resolver $layerResolver,
JsonFactory $resultJsonFactory,
PageFactory $resultPageFactory,
CatalogSearchHelper $catalogSearchHelper,
WpHelper $wpHelper
) {
$this->_storeManager = $storeManager;
$this->_queryFactory = $queryFactory;
$this->layerResolver = $layerResolver;
$this->_resultJsonFactory = $resultJsonFactory;
$this->_resultPageFactory = $resultPageFactory;
$this->_catalogSearchHelper = $catalogSearchHelper;
$this->_wpHelper = $wpHelper;
}
/**
* @param \Magento\CatalogSearch\Controller\Result\Index $subject
* @param \Closure $method
* @return $this|array|mixed
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function aroundExecute(
\Magento\CatalogSearch\Controller\Result\Index $subject,
\Closure $method
) {
if ($subject->getRequest()->getParam('ajax') == 1 && $this->_wpHelper->isEnabled()) {
$this->_wpHelper->updateSliderBodyClass();
$requestUri = $subject->getRequest()->getRequestUri();
$requestUri = preg_replace('/(\?|&)ajax=1/', '', $requestUri);
$subject->getRequest()->setRequestUri($requestUri);
try {
$this->layerResolver->create(Resolver::CATALOG_LAYER_SEARCH);
} catch (\Exception $ex) {
}
/* @var $query \Magento\Search\Model\Query */
$query = $this->_queryFactory->get();
$query->setStoreId($this->_storeManager->getStore()->getId());
$resultJson = $this->_resultJsonFactory->create();
if ($query->getQueryText() != '') {
if ($this->_catalogSearchHelper->isMinQueryLength()) {
$query->setId(0)->setIsActive(1)->setIsProcessed(1);
} else {
$query->saveIncrementalPopularity();
if ($query->getRedirect()) {
$data = [
'success' => true,
'redirect_url' => $query->getRedirect()
];
return $resultJson->setData($data);
}
}
$this->_catalogSearchHelper->checkNotes();
$pageFactory = $this->_resultPageFactory->create();
$resultsBlockHtml = $pageFactory->getLayout()->getBlock('search.result')->toHtml();
$leftNavBlockHtml = $pageFactory->getLayout()->getBlock('catalogsearch.leftnav')->toHtml();
$dataLayerContent = '';
$dataLayerContentGa4 = '';
$dataLayerBlock = $pageFactory->getLayout()->getBlock('head.additional');
if ($dataLayerBlock) {
$dLBlockHtml = $dataLayerBlock->toHtml();
preg_match('/var dlObjects ?= ?(.*?)];/', $dLBlockHtml, $matches);
if (count($matches) == 2) {
$dataLayerContent = $matches[1] . ']';
}
preg_match('/var dl4Objects ?= ?(.*?)];/', $dLBlockHtml, $matchesGa4);
if (count($matchesGa4) == 2) {
$dataLayerContentGa4 = $matchesGa4[1] . ']';
}
}
$ga4ServerSideViewItemListContent = '';
$ga4ServerSideViewItemListBlock = $pageFactory->getLayout()->getBlock('weltpixel-ga4-server-view-item-list');
if ($ga4ServerSideViewItemListBlock) {
$ga4ServerSideViewItemListBlockHtml = $ga4ServerSideViewItemListBlock->toHtml();
preg_match('/<input.*id="wp_ga4_server_side_view_item_list".*value="(.*?)"/', $ga4ServerSideViewItemListBlockHtml, $matchesGa4ServerSide);
if (count($matchesGa4ServerSide) == 2) {
$ga4ServerSideViewItemListContent = $matchesGa4ServerSide[1];
}
}
return $this->_resultJsonFactory->create()->setData(
[
'success' => true,
'html' => [
'products_list' => $resultsBlockHtml,
'filters' => $leftNavBlockHtml,
'dataLayer' => $dataLayerContent,
'dataLayerGA4' => $dataLayerContentGa4,
'ga4ServerSideItemListHash' => $ga4ServerSideViewItemListContent
]
]
);
} else {
$data = [
'success' => true,
'redirect_url' => $this->_redirect->getRedirectUrl()
];
return $resultJson->setData($data);
}
} else {
return $method();
}
}
}
@@ -0,0 +1,103 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Plugin\Category;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\Product;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\View\Result\Page;
use Magento\Framework\UrlInterface;
use WeltPixel\LayeredNavigation\Helper\Data;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Action;
use WeltPixel\NavigationLinks\Model\Attribute\Source\CategoryLayout;
/**
* Class Design
* @package WeltPixel\LayeredNavigation\Plugin\Category
*/
class Design
{
/**
* @var JsonFactory
*/
protected $_resultJsonFactory;
/**
* @var UrlInterface
*/
protected $_storeManager;
/**
* @var \WeltPixel\LayeredNavigation\Helper\Data
*/
protected $_wpHelper;
/**
* @var PageFactory
*/
protected $pageFactory;
/**
* View constructor.
* @param JsonFactory $resultJsonFactory
* @param UrlInterface $_storeManager
* @param Data $wpHelper
* @param PageFactory $pageFactory
*/
public function __construct(
JsonFactory $resultJsonFactory,
UrlInterface $_storeManager,
Data $wpHelper,
PageFactory $pageFactory
)
{
$this->_resultJsonFactory = $resultJsonFactory;
$this->_storeManager = $_storeManager;
$this->_wpHelper = $wpHelper;
$this->pageFactory = $pageFactory;
}
/**
* @param \Magento\Catalog\Model\Design $subject
* @param \Magento\Framework\DataObject $result
* @param Category|Product $object
* @return \Magento\Framework\DataObject
*/
public function afterGetDesignSettings(\Magento\Catalog\Model\Design $subject, $result, $object)
{
if(!$this->_wpHelper->isEnabled()) {
return $result;
}
if ($object instanceof Product) {
$currentCategory = $object->getCategory();
} else {
$currentCategory = $object;
}
if (!$currentCategory) {
return $result;
}
$sideBarStyle = $this->_wpHelper->getSidebarStyle();
if ($sideBarStyle != 3) {
return $result;
}
$result->setPageLayout('1column');
$pageLayoutHandles = $result->getPageLayoutHandles();
$horizontalLayoutHandle = ['wpln' => 'horizontalnavigation'];
if (is_array($pageLayoutHandles)) {
$pageLayoutHandles['wpln'] = 'horizontalnavigation';
} else {
$pageLayoutHandles = $horizontalLayoutHandle;
}
$result->setPageLayoutHandles($pageLayoutHandles);
return $result;
}
}
@@ -0,0 +1,144 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Plugin\Category;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\View\Result\Page;
use Magento\Framework\UrlInterface;
use WeltPixel\LayeredNavigation\Helper\Data;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Action;
/**
* Class View
* @package WeltPixel\LayeredNavigation\Plugin\Category
*/
class View
{
/**
* @var JsonFactory
*/
protected $_resultJsonFactory;
/**
* @var UrlInterface
*/
protected $_storeManager;
/**
* @var \WeltPixel\LayeredNavigation\Helper\Data
*/
protected $_wpHelper;
/**
* @var PageFactory
*/
protected $pageFactory;
/**
* View constructor.
* @param JsonFactory $resultJsonFactory
* @param UrlInterface $_storeManager
* @param Data $wpHelper
* @param PageFactory $pageFactory
*/
public function __construct(
JsonFactory $resultJsonFactory,
UrlInterface $_storeManager,
Data $wpHelper,
PageFactory $pageFactory
)
{
$this->_resultJsonFactory = $resultJsonFactory;
$this->_storeManager = $_storeManager;
$this->_wpHelper = $wpHelper;
$this->pageFactory = $pageFactory;
}
/**
* @param Action $subject
* @param $page
* @return $this|void
*/
public function afterExecute(Action $subject, $page)
{
if ($this->_wpHelper->isEnabled()) {
$this->_wpHelper->updateSliderBodyClass();
}
if(!$this->_wpHelper->isAjaxEnabled() || !$this->_wpHelper->isEnabled()) {
return $page;
}
$response = $page;
if ($response instanceof Page) {
if ($subject->getRequest()->getParam('ajax') == 1) {
$subject->getRequest()->getQuery()->set('ajax', null);
$requestUri = $subject->getRequest()->getRequestUri();
$requestUri = preg_replace('/(\?|&)ajax=1/', '', $requestUri);
$subject->getRequest()->setRequestUri($requestUri);
$productsList = $response->getLayout()->getBlock('category.products.list');
$listMode = $subject->getRequest()->getParam('product_list_mode');
if($listMode) {
$productsList->getChildBlock('product_list_toolbar')->setData('_current_grid_mode', $listMode);
}
$productsListBlockHtml = $productsList->toHtml();
$leftNavBlockHtml = $response->getLayout()->getBlock('catalog.leftnav')->toHtml();
$dataLayerContent = '';
$dataLayerContentGa4 = '';
$dataLayerBlock = $response->getLayout()->getBlock('head.additional');
if ($dataLayerBlock) {
$dLBlockHtml = $dataLayerBlock->toHtml();
preg_match('/var dlObjects ?= ?(.*?)];/', $dLBlockHtml, $matches);
if (count($matches) == 2) {
$dataLayerContent = $matches[1] . ']';
}
preg_match('/var dl4Objects ?= ?(.*?)];/', $dLBlockHtml, $matchesGa4);
if (count($matchesGa4) == 2) {
$dataLayerContentGa4 = $matchesGa4[1] . ']';
}
}
$ga4ServerSideViewItemListContent = '';
$ga4ServerSideViewItemListBlock = $response->getLayout()->getBlock('weltpixel-ga4-server-view-item-list');
if ($ga4ServerSideViewItemListBlock) {
$ga4ServerSideViewItemListBlockHtml = $ga4ServerSideViewItemListBlock->toHtml();
preg_match('/<input.*id="wp_ga4_server_side_view_item_list".*value="(.*?)"/', $ga4ServerSideViewItemListBlockHtml, $matchesGa4ServerSide);
if (count($matchesGa4ServerSide) == 2) {
$ga4ServerSideViewItemListContent = $matchesGa4ServerSide[1];
}
}
$tags = [];
$blocksList = [$productsList,$leftNavBlockHtml];
foreach ($blocksList as $block) {
if ($block instanceof \Magento\Framework\DataObject\IdentityInterface) {
$tags = array_merge($tags, $block->getIdentities());
}
}
$tags = array_unique($tags);
return $this->_resultJsonFactory->create()->setData(
[
'success' => true,
'html' => [
'products_list' => $productsListBlockHtml,
'filters' => $leftNavBlockHtml,
'dataLayer' => $dataLayerContent,
'dataLayerGA4' => $dataLayerContentGa4,
'ga4ServerSideItemListHash' => $ga4ServerSideViewItemListContent
]
]
)->setHeader('X-Magento-Tags', implode(',', $tags));
}
}
return $response;
}
}
@@ -0,0 +1,145 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Plugin\Layer;
use WeltPixel\LayeredNavigation\Helper\Data;
/**
* Class FilterList
* @package WeltPixel\LayeredNavigation\Plugin\Layer
*/
class FilterList
{
const RATING_FILTER_CLASS = 'WeltPixel\LayeredNavigation\Model\Layer\Filter\Rating';
/**
* @var \WeltPixel\LayeredNavigation\Helper\Data
*/
protected $_wpHelper;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $_objectManager;
/**
* @var \Magento\Catalog\Model\Layer
*/
protected $_layer;
/**
* FilterList constructor.
* @param Data $wpHelper
* @param \Magento\Framework\ObjectManagerInterface $objectManager
*/
public function __construct(
Data $wpHelper,
\Magento\Framework\ObjectManagerInterface $objectManager
)
{
$this->_wpHelper = $wpHelper;
$this->_objectManager = $objectManager;
}
/**
* Remove category filter if disabled in configuration
*
* @param \Magento\Catalog\Model\Layer\FilterList $subject
* @param $result
* @return array
*/
public function afterGetFilters(\Magento\Catalog\Model\Layer\FilterList $subject, $result)
{
if(!$this->_wpHelper->isEnabled()){
return $result;
}
$filteredResult = [];
if(!$this->_wpHelper->showCategoriesBlock()) {
foreach($result as $r) {
if($r->getRequestVar() != $this->_wpHelper->getCategoryParamLabel()) {
$filteredResult[] = $r;
}
}
return $filteredResult;
} else {
return $result;
}
}
/**
* @param \Magento\Catalog\Model\Layer\FilterList $subject
* @param \Closure $proceed
* @param \Magento\Catalog\Model\Layer $layer
* @return array|mixed
*/
public function aroundGetFilters( \Magento\Catalog\Model\Layer\FilterList $subject, \Closure $proceed, \Magento\Catalog\Model\Layer $layer)
{
if(!$this->_wpHelper->isEnabled()){
$result = $proceed($layer);
return $result;
}
$result = $proceed($layer);
if($this->_wpHelper->getRatingFilterName()) {
$result[] = $this->getRatingFilter($layer);
$result = $this->_injectRatingFilter($result);
}
return $result;
}
/**
* @param $filters
* @return mixed
*/
protected function _injectRatingFilter($filters) {
$ratingFilterPosition = $this->_wpHelper->getRatingFilterPosition();
if(count($filters) > $ratingFilterPosition) {
foreach($filters as $k => $filter) {
$class = self::RATING_FILTER_CLASS;
if($filter instanceof $class){
$ratingFilterKey = $k;
break;
}
}
$ratingFilterArr = array_splice($filters, $ratingFilterKey, 1);
array_splice($filters, $ratingFilterPosition, 0, $ratingFilterArr);
}
return $filters;
}
/**
* @param $layer
* @return mixed
*/
public function getRatingFilter($layer)
{
$filter = $this->_objectManager->create(
$this->getRatingFilterClass(),
['layer' => $layer]
);
return $filter;
}
/**
* @return string
*/
public function getRatingFilterClass() {
return self::RATING_FILTER_CLASS;
}
}
@@ -0,0 +1,130 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Plugin\Model\Layer\Filter;
use WeltPixel\LayeredNavigation\Helper\Data as LayerHelper;
use WeltPixel\LayeredNavigation\Model\Layer\Filter as FilterModel;
/**
* Class Item
* @package WeltPixel\LayeredNavigation\Model\Plugin\Layer\Filter
*/
class Item
{
/** @var \Magento\Framework\UrlInterface */
protected $_url;
/** @var \Magento\Theme\Block\Html\Pager */
protected $_htmlPagerBlock;
/** @var \Magento\Framework\App\RequestInterface */
protected $_request;
/** @var \WeltPixel\LayeredNavigation\Helper\Data */
protected $_wpHelper;
/**
* @var FilterModel
*/
protected $_filterModel;
/**
* Item constructor.
* @param \Magento\Framework\UrlInterface $url
* @param \Magento\Theme\Block\Html\Pager $htmlPagerBlock
* @param \Magento\Framework\App\RequestInterface $request
* @param LayerHelper $_wpHelper
* @param FilterModel $filterModel
*/
public function __construct(
\Magento\Framework\UrlInterface $url,
\Magento\Theme\Block\Html\Pager $htmlPagerBlock,
\Magento\Framework\App\RequestInterface $request,
LayerHelper $wpHelper,
FilterModel $filterModel
)
{
$this->_url = $url;
$this->_htmlPagerBlock = $htmlPagerBlock;
$this->_request = $request;
$this->_wpHelper = $wpHelper;
$this->_filterModel = $filterModel;
}
/**
* @param \Magento\Catalog\Model\Layer\Filter\Item $item
* @param $proceed
* @return string
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function aroundGetRemoveUrl(\Magento\Catalog\Model\Layer\Filter\Item $item, $proceed)
{
if (!$this->_wpHelper->isEnabled()) {
return $proceed();
}
$value = [];
$filter = $item->getFilter();
$value = $this->_filterModel->getFilterValue($filter);
$itemValue = $item->getValue();
if (is_array($item->getValue())) {
$itemValue = implode('-', $item->getValue());
}
if (in_array($itemValue, $value)) {
$value = array_diff($value, [$itemValue]);
}
$params['_query'] = [$filter->getRequestVar() => count($value) ? implode(',', $value) : $filter->getResetValue()];
$params['_current'] = true;
$params['_use_rewrite'] = true;
$params['_escape'] = true;
return $this->_url->getUrl('*/*/*', $params);
}
/**
* @param \Magento\Catalog\Model\Layer\Filter\Item $item
* @param $proceed
* @return string
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function aroundGetUrl(\Magento\Catalog\Model\Layer\Filter\Item $item, $proceed)
{
if (!$this->_wpHelper->isEnabled() || $this->_wpHelper->isAjaxEnabled()) {
return $proceed();
}
$filter = $item->getFilter();
if ($filter instanceof \WeltPixel\LayeredNavigation\Model\Layer\Filter\Rating
|| $filter instanceof \WeltPixel\LayeredNavigation\Model\Layer\Filter\Category) {
$isMultiSelect = false;
} else {
$isMultiSelect = $this->_filterModel->isMultiselect($filter->getAttributeModel()->getAttributeId());
}
if (!$isMultiSelect) {
return $proceed();
}
$requestVarValue = $this->_filterModel->getFilterValue($filter);
if (in_array($item->getValue(), $requestVarValue)) {
$requestVarValue = array_diff($requestVarValue, [$item->getValue()]);
} else {
array_push($requestVarValue, $item->getValue());
}
$requestVarValue = implode(",", $requestVarValue);
$query = [
$filter->getRequestVar() => $requestVarValue,
$this->_htmlPagerBlock->getPageVarName() => null,
];
return $this->_url->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true, '_query' => $query]);
}
}
@@ -0,0 +1,111 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Plugin\Swatches;
use WeltPixel\LayeredNavigation\Helper\Data as LayerHelper;
use WeltPixel\LayeredNavigation\Model\Layer\Filter as FilterModel;
/**
* Class RenderLayered
* @package WeltPixel\LayeredNavigation\Plugin\Swatches
*/
class RenderLayered
{
/** @var \Magento\Framework\UrlInterface */
protected $_url;
/** @var \Magento\Theme\Block\Html\Pager */
protected $_htmlPagerBlock;
/** @var \Magento\Framework\App\RequestInterface */
protected $_request;
/** @var \WeltPixel\LayeredNavigation\Helper\Data */
protected $_wpHelper;
/**
* @var FilterModel
*/
protected $_filterModel;
/**
* @var \Magento\Eav\Model\ResourceModel\Entity\Attribute
*/
protected $eavAttribute;
/**
* Item constructor.
* @param \Magento\Framework\UrlInterface $url
* @param \Magento\Theme\Block\Html\Pager $htmlPagerBlock
* @param \Magento\Framework\App\RequestInterface $request
* @param LayerHelper $_wpHelper
* @param FilterModel $filterModel
* @param \Magento\Eav\Model\ResourceModel\Entity\Attribute $eavAttribute
*/
public function __construct(
\Magento\Framework\UrlInterface $url,
\Magento\Theme\Block\Html\Pager $htmlPagerBlock,
\Magento\Framework\App\RequestInterface $request,
LayerHelper $wpHelper,
FilterModel $filterModel,
\Magento\Eav\Model\ResourceModel\Entity\Attribute $eavAttribute
) {
$this->_url = $url;
$this->_htmlPagerBlock = $htmlPagerBlock;
$this->_request = $request;
$this->_wpHelper = $wpHelper;
$this->_filterModel = $filterModel;
$this->eavAttribute = $eavAttribute;
}
/**
* @param \Magento\Swatches\Block\LayeredNavigation\RenderLayered $renderLayered
* @param $proceed
* @param string $attributeCode
* @param int $optionId
* @return string
*/
public function aroundBuildUrl(
\Magento\Swatches\Block\LayeredNavigation\RenderLayered $renderLayered,
$proceed,
$attributeCode,
$optionId
) {
if (!$this->_wpHelper->isEnabled() || $this->_wpHelper->isAjaxEnabled()) {
return $proceed($attributeCode, $optionId);
}
$attributeId = $this->eavAttribute->getIdByCode('catalog_product', $attributeCode);
$isMultiSelect = $this->_filterModel->isMultiselect($attributeId);
if (!$isMultiSelect) {
return $proceed($attributeCode, $optionId);
}
$filterValue = $this->_request->getParam($attributeCode);
$requestVarValue = [];
if (!empty($filterValue)) {
$requestVarValue = explode(',', $filterValue);
}
if (in_array($optionId, $requestVarValue)) {
$requestVarValue = array_diff($requestVarValue, [$optionId]);
} else {
array_push($requestVarValue, $optionId);
}
$requestVarValue = implode(",", $requestVarValue);
$query = [
$attributeCode => $requestVarValue,
$this->_htmlPagerBlock->getPageVarName() => null
];
return $this->_url->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true, '_query' => $query]);
}
}
+35
View File
@@ -0,0 +1,35 @@
# magento2-weltpixel-layered-navigation
### Installation
Dependencies:
- magento2-weltpixel-backend (see https://github.com/Weltpixel/magento2-weltpixel-backend)
With composer:
```sh
$ composer config repositories.weltpixel-magento2-weltpixel-backend git https://github.com/Weltpixel/magento2-weltpixel-backend.git
$ composer require weltpixel/magento2-weltpixel-backend:dev-master
$ composer config repositories.weltpixel-magento2-weltpixel-layered-navigation git https://github.com/Weltpixel/magento2-weltpixel-layered-navigation.git
$ composer require weltpixel/magento2-weltpixel-layered-navigation:dev-master
```
Manually:
Important: Ensure you also install the shared Backend module. If it's already installed, you can skip this. Details in the repo at https://github.com/Weltpixel/magento2-weltpixel-backend.
Copy the zip into app/code/WeltPixel/LayeredNavigation directory
#### After installation by either means, enable the extension by running following commands:
```sh
$ php bin/magento module:enable WeltPixel_LayeredNavigation --clear-static-content
$ php bin/magento setup:upgrade
```
### Documentation
For detailed documentation, please visit: https://github.com/Weltpixel/magento2-weltpixel-documentation/tree/master/Magento2/LayeredNavigation
@@ -0,0 +1,125 @@
<?php
namespace WeltPixel\LayeredNavigation\Setup\Patch\Schema;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\Patch\SchemaPatchInterface;
use Magento\Framework\Setup\Patch\PatchVersionInterface;
class AddAttributeOptionsTable implements SchemaPatchInterface, PatchVersionInterface
{
/**
* @var SchemaSetupInterface $schemaSetup
*/
private $schemaSetup;
/**
* @param SchemaSetupInterface $schemaSetup
*/
public function __construct(SchemaSetupInterface $schemaSetup)
{
$this->schemaSetup = $schemaSetup;
}
/**
* {@inheritdoc}
*/
public function apply()
{
$setup = $this->schemaSetup;
$this->schemaSetup->startSetup();
/**
* Create table 'weltpixel_ln_attribute_options'
*/
$table = $setup->getConnection()->newTable(
$setup->getTable('weltpixel_ln_attribute_options')
)->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Id'
)->addColumn(
'attribute_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Attribute Id'
)->addColumn(
'display_option',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Filter Display Option'
)->addColumn(
'visible_options',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '99'],
'Initial number of options'
)->addColumn(
'visible_options_step',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '99'],
'Expandable items behaviour'
)->addColumn(
'is_multiselect',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Enable Multiselect'
)->addColumn(
'show_quantity',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Show Quantity'
)->addColumn(
'sort_by',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '1'],
'Sort By'
)->addIndex(
$setup->getIdxName($setup->getTable('weltpixel_ln_attribute_options'),['id']),
['id']
)->addForeignKey(
$setup->getFkName('weltpixel_ln_attribute_options', 'attribute_id', 'eav_attribute', 'attribute_id'),
'attribute_id',
$setup->getTable('eav_attribute'),
'attribute_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->setComment(
'WeltPixel Layered Navigation Attribute Options'
);
$setup->getConnection()->createTable($table);
$this->schemaSetup->endSetup();
}
/**
* {@inheritdoc}
*/
public static function getVersion()
{
return '1.0.0';
}
/**
* @inheritdoc
*/
public function getAliases()
{
return [];
}
/**
* @inheritdoc
*/
public static function getDependencies()
{
return [];
}
}
@@ -0,0 +1,108 @@
<?php
namespace WeltPixel\LayeredNavigation\Setup\Patch\Schema;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\Patch\SchemaPatchInterface;
use Magento\Framework\Setup\Patch\PatchVersionInterface;
class ModifyAttributeOptionsTableColumns implements SchemaPatchInterface, PatchVersionInterface
{
/**
* @var SchemaSetupInterface $schemaSetup
*/
private $schemaSetup;
/**
* @param SchemaSetupInterface $schemaSetup
*/
public function __construct(SchemaSetupInterface $schemaSetup)
{
$this->schemaSetup = $schemaSetup;
}
/**
* {@inheritdoc}
*/
public function apply()
{
$setup = $this->schemaSetup;
$setup->startSetup();
$connection = $setup->getConnection();
$tableName = $setup->getTable('weltpixel_ln_attribute_options');
if ($setup->getConnection()->isTableExists($tableName)) {
$columns = [
'instant_search' => [
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'default' => 0,
'unsigned' => true,
'nullable' => false,
'comment' => 'Instant Search Desktop',
],
'instant_search_mobile' => [
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'default' => 0,
'unsigned' => true,
'nullable' => false,
'comment' => 'Instant Search Mobile',
],
'category_visibility' => [
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'default' => 0,
'unsigned' => true,
'nullable' => false,
'comment' => 'Category Visibility',
],
'category_ids' => [
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'unsigned' => true,
'nullable' => true,
'comment' => 'Categories ids list',
],
'keep_open_after_filter' => [
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'default' => 0,
'unsigned' => true,
'nullable' => false,
'comment' => 'Keep attribute opened after filtering',
'after' => 'is_multiselect'
]
];
foreach ($columns as $name => $definition) {
if (!$connection->tableColumnExists($tableName, $name)) {
$connection->addColumn($tableName, $name, $definition);
}
}
}
$setup->endSetup();
}
/**
* {@inheritdoc}
*/
public static function getVersion()
{
return '1.0.4';
}
/**
* @inheritdoc
*/
public function getAliases()
{
return [];
}
/**
* @inheritdoc
*/
public static function getDependencies()
{
return [
AddAttributeOptionsTable::class
];
}
}
+18
View File
@@ -0,0 +1,18 @@
{
"name": "weltpixel/magento2-weltpixel-layered-navigation",
"description": "WeltPixel LayeredNavigation Module",
"replace": {
"weltpixel/magento2-weltpixel-layered-navigation-lite": "self.version"
},
"type": "magento2-module",
"version": "1.16.0",
"license": "MIT",
"autoload": {
"files": [
"registration.php"
],
"psr-4": {
"WeltPixel\\LayeredNavigation\\": ""
}
}
}
+33
View File
@@ -0,0 +1,33 @@
<?xml version="1.0"?>
<!--
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
<acl>
<resources>
<resource id="Magento_Backend::admin">
<resource id="WeltPixel_Backend::WeltPixel">
<resource id="WeltPixel_LayeredNavigation::LayeredNavigation_Label" sortOrder="90"
title="LayeredNavigation">
<resource id="WeltPixel_LayeredNavigation::LayeredNavigation_General" sortOrder="10"
title="LayeredNavigation Settings"/>
</resource>
</resource>
<resource id="Magento_Backend::stores">
<resource id="Magento_Backend::stores_settings">
<resource id="Magento_Config::config">
<resource id="WeltPixel_LayeredNavigation::LayeredNavigation"
title="WeltPixel LayeredNavigation" sortOrder="283"/>
</resource>
</resource>
</resource>
</resource>
</resources>
</acl>
</config>
@@ -0,0 +1,17 @@
<?xml version="1.0"?>
<!--
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="product_attribute_form_build_weltpixel_layerednavigation_tab">
<observer name="wp_layeredNavigation" instance="WeltPixel\LayeredNavigation\Observer\Edit\Tab\Front\WpProductAttributeFormBuildFrontTabObserver" />
</event>
<event name="catalog_entity_attribute_save_after">
<observer name="wp_layeredNavigation_attribute_options" instance="WeltPixel\LayeredNavigation\Observer\WpCatalogAttributeSaveAfterObserver" />
</event>
</config>
@@ -0,0 +1,31 @@
<?xml version="1.0"?>
<!--
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
<menu>
<add
id="WeltPixel_LayeredNavigation::LayeredNavigation_Label"
title="Layered Navigation Pro"
module="WeltPixel_LayeredNavigation"
sortOrder="390"
parent="WeltPixel_Backend::WeltPixel"
resource="WeltPixel_LayeredNavigation::LayeredNavigation_Label"
/>
<add
id="WeltPixel_LayeredNavigation::LayeredNavigation_General"
title="Layered Navigation Settings"
module="WeltPixel_LayeredNavigation"
action="adminhtml/system_config/edit/section/weltpixel_layerednavigation/"
sortOrder="10"
parent="WeltPixel_LayeredNavigation::LayeredNavigation_Label"
resource="WeltPixel_LayeredNavigation::LayeredNavigation_General"
/>
</menu>
</config>
@@ -0,0 +1,420 @@
<?xml version="1.0"?>
<!--
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<section id="weltpixel_layerednavigation" showInDefault="1" showInStore="1" showInWebsite="1" sortOrder="210"
translate="label">
<label>Layered Navigation Pro</label>
<tab>weltpixel</tab>
<resource>WeltPixel_LayeredNavigation::LayeredNavigation</resource>
<group id="general" showInDefault="1" showInStore="1" showInWebsite="1" sortOrder="10" translate="label">
<label>General Settings</label>
<field id="enable" showInDefault="1" showInStore="1" showInWebsite="1" sortOrder="10" translate="label"
type="select">
<label>Enable Layered Navigation</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment>Enable/Disable WeltPixel Layered Navigation.</comment>
</field>
<field id="ajax" showInDefault="1" showInStore="1" showInWebsite="1" sortOrder="30"
translate="label" type="select">
<label>Enable Ajax</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment>Enable/Disable Ajax Layered Navigation.</comment>
<depends>
<field id="enable">1</field>
</depends>
</field>
<field id="ajax_scroll_top" showInDefault="1" showInStore="1" showInWebsite="1" sortOrder="32"
translate="label" type="select">
<label>Scroll to top after Ajax load</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<depends>
<field id="enable">1</field>
<field id="ajax">1</field>
</depends>
</field>
</group>
<group id="sidebar" showInDefault="1" showInStore="1" showInWebsite="1" sortOrder="20" translate="label">
<label>Sidebar Settings</label>
<field id="info_message" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<frontend_model>WeltPixel\LayeredNavigation\Block\Adminhtml\System\Config\InfoMessage</frontend_model>
</field>
<field id="sb_style" translate="label" type="select" sortOrder="10" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Sidebar Style</label>
<source_model>WeltPixel\LayeredNavigation\Model\Config\Source\SidebarStyle</source_model>
<comment><![CDATA[Select the preferred style for the Layered Navigation sidebar block. <br/>
If one of the 'Slide In' or 'Slide Down' option is selected, the 'Compare Products' and 'Wish List' blocks will be removed from the sidebar. <br/>
Note: Make sure the layout for category/listing pages is set to 2-columns-left.
]]>
</comment>
<depends>
<field id="weltpixel_layerednavigation/general/enable">1</field>
</depends>
</field>
<field id="slide_down_columns" translate="label" type="select" sortOrder="10" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Columns No.</label>
<source_model>WeltPixel\LayeredNavigation\Model\Config\Source\SlideDownFilterColumns</source_model>
<tooltip>Set the number of columns to appear in slide down box / 1 line.</tooltip>
<comment>Number of columns to appear in Slide Down Filter Box in 1 line.</comment>
<depends>
<field id="sb_style">2</field>
</depends>
</field>
<field id="horizontal_sb_design_version" translate="label" type="select" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Horizontal Design Version</label>
<source_model>WeltPixel\LayeredNavigation\Model\Config\Source\HorizontalSidebarDesignVersion</source_model>
<depends>
<field id="weltpixel_layerednavigation/general/enable">1</field>
<field id="sb_style">3</field>
</depends>
</field>
<field id="horizontal_sb_design_v2_filter_position" translate="label" type="select" sortOrder="25" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Filter Alignment</label>
<source_model>WeltPixel\LayeredNavigation\Model\Config\Source\HorizontalSidebarFilterPosition</source_model>
<depends>
<field id="weltpixel_layerednavigation/general/enable">1</field>
<field id="sb_style">3</field>
<field id="horizontal_sb_design_version">v2</field>
</depends>
</field>
<field id="horizontal_sb_sticky_enable" translate="label comment" type="select" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Enable Sticky Filters</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<depends>
<field id="weltpixel_layerednavigation/general/enable">1</field>
<field id="sb_style">3</field>
<field id="horizontal_sb_design_version">v2</field>
</depends>
</field>
<field id="sb_selected_filters_options" translate="label comment" type="select" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Display Selected Filters</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<depends>
<field id="weltpixel_layerednavigation/general/enable">1</field>
</depends>
<comment>
<![CDATA[If set to "Yes", filters that have been selected will be displayed under the Layered Navigation. </br>
If set to "No", the user will not see the filters they select, and only a "Clear All" button will be shown. ]]>
</comment>
</field>
<field id="display_multiselect_selected_options" translate="label comment" type="select" sortOrder="33" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Display Multiselect Attributes Selected Options Counter</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<depends>
<field id="weltpixel_layerednavigation/general/enable">1</field>
</depends>
</field>
<field id="slide_down_height" translate="label" type="text" sortOrder="35" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Filter Box Height</label>
<comment>Slide Down Filter Box Height. Eg.500px</comment>
<tooltip>Set the height of slide down box.</tooltip>
<depends>
<field id="sb_style">2</field>
</depends>
</field>
<field id="horizontal_box_shadow" translate="label comment" type="select" sortOrder="36" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Box Shadow</label>
<comment>Enable to display a shadow for the Layered Navigation Slide Down box.</comment>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<depends>
<field id="sb_style">2</field>
</depends>
</field>
<field id="horizontal_v3_filters_button_color" translate="label" type="text" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Filter Button Color</label>
<comment>Choose the color of the filter buttons.</comment>
<depends>
<field id="sb_style">3</field>
<field id="horizontal_sb_design_version">v3</field>
</depends>
<validate>color {required:false, hash:true}</validate>
</field>
<field id="horizontal_v3_filters_text_color" translate="label" type="text" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Filter Button Text Color</label>
<comment>Choose the color of the text displayed on filter buttons.</comment>
<depends>
<field id="sb_style">3</field>
<field id="horizontal_sb_design_version">v3</field>
</depends>
<validate>color {required:false, hash:true}</validate>
</field>
<field id="horizontal_v3_filters_button_hover_color" translate="label" type="text" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Filter Button Hover Color</label>
<comment>Choose the color of the filter buttons when hovered upon.</comment>
<depends>
<field id="sb_style">3</field>
<field id="horizontal_sb_design_version">v3</field>
</depends>
<validate>color {required:false, hash:true}</validate>
</field>
<field id="horizontal_v3_filters_text_hover_color" translate="label" type="text" sortOrder="40" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Filter Button Hover Text Color</label>
<comment>Choose the color of the text displayed on filter buttons when hovered upon.</comment>
<depends>
<field id="sb_style">3</field>
<field id="horizontal_sb_design_version">v3</field>
</depends>
<validate>color {required:false, hash:true}</validate>
</field>
<field id="horizontal_v3_border" translate="label" type="text" sortOrder="40" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Border</label>
<comment>Eg. 1px solid</comment>
<depends>
<field id="sb_style">3</field>
<field id="horizontal_sb_design_version">v3</field>
</depends>
</field>
<field id="horizontal_v3_border_color" translate="label" type="text" sortOrder="45" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Border Color</label>
<comment>Choose the color of the filter buttons border.</comment>
<depends>
<field id="sb_style">3</field>
<field id="horizontal_sb_design_version">v3</field>
</depends>
<validate>color {required:false, hash:true}</validate>
</field>
<field id="horizontal_v3_border_radius" translate="label" type="text" sortOrder="50" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Border Radius</label>
<comment>Eg. 35px</comment>
<depends>
<field id="sb_style">3</field>
<field id="horizontal_sb_design_version">v3</field>
</depends>
</field>
<field id="filter_column_height" translate="label" type="text" sortOrder="55" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Filter Column Height</label>
<comment>Slide Down Filter Column Height. Eg.250px</comment>
<tooltip>Set the height of the filter options column.</tooltip>
<depends>
<field id="sb_style">2</field>
</depends>
</field>
<field id="allow_layered_show_hide" translate="label comment" type="select" sortOrder="60" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Allow customer to show/hide Layered Navigation</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<depends>
<field id="sb_style">0</field>
</depends>
</field>
<field id="layered_show_hide_state" translate="label" type="select" sortOrder="65" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Filters default state</label>
<source_model>WeltPixel\LayeredNavigation\Model\Config\Source\FilterShowHideState</source_model>
<depends>
<field id="sb_style">0</field>
<field id="allow_layered_show_hide">1</field>
</depends>
</field>
<field id="compare_block" translate="label comment" type="select" sortOrder="70" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Show Compare Products block</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment>Show/Hide Compare Products block from Sidebar Style - Default.</comment>
<depends>
<field id="sb_style">0</field>
</depends>
</field>
<field id="wishlist_block" translate="label comment" type="select" sortOrder="75" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Show Wish List block</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment>Show/Hide Wish List block from Sidebar Style - Default.</comment>
<depends>
<field id="sb_style">0</field>
</depends>
</field>
<field id="recentlyordered_block" translate="label comment" type="select" sortOrder="80" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Show Recently Ordered block</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment>Show/Hide Recently Ordered block from Sidebar Style - Default.</comment>
<depends>
<field id="sb_style">0</field>
</depends>
</field>
<field id="category_block" translate="label" type="select" sortOrder="85" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Show Category Filter</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment>
<![CDATA[Show/Hide Category Filter section from Layered Navigation sidebar.<br/>
Applicable to Anchor categories. <br/>
Also, if exists, make sure to set Stores > Configuration > Catalog > Catalog > Layered Navigation > Display Category Filter to Yes.
]]>
</comment>
<depends>
<field id="weltpixel_layerednavigation/general/enable">1</field>
</depends>
</field>
<field id="show_category_filter_as" translate="label" type="select" sortOrder="86" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Show Category Filter Options as</label>
<source_model>WeltPixel\LayeredNavigation\Model\Config\Source\CategoryShowAs</source_model>
<depends>
<field id="weltpixel_layerednavigation/general/enable">1</field>
<field id="weltpixel_layerednavigation/sidebar/category_block">1</field>
</depends>
</field>
<field id="filter_button" translate="label" type="select" sortOrder="90" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Filter Button</label>
<source_model>WeltPixel\LayeredNavigation\Model\Config\Source\FilterButton</source_model>
<comment>Select the preferred style for the Layered Navigation filter button.</comment>
<depends>
<field id="sb_style" separator=",">1,2</field>
</depends>
</field>
<comment>
<![CDATA[
<script type="text/javascript">
require(['jquery', 'domReady!'], function(){
if (jQuery('#weltpixel_layerednavigation_general_enable').val() != 1){
jQuery('#weltpixel_layerednavigation_sidebar').closest('.section-config').hide();
}
jQuery('#weltpixel_layerednavigation_general_enable').on('change', function(){
if (this.value != 1){
jQuery('#weltpixel_layerednavigation_sidebar').closest('.section-config').hide();
} else {
jQuery('#weltpixel_layerednavigation_sidebar').closest('.section-config').show();
}
})
});
</script>
]]>
</comment>
<field id="price_filter" translate="label" type="select" sortOrder="95" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Price Filter</label>
<source_model>WeltPixel\LayeredNavigation\Model\Config\Source\PriceFilter</source_model>
<comment><![CDATA[
Select the preferred style for the Layered Navigation price filter.<br />
Note: If Price Filter is set to “Slider“, the ‘Stores > Configuration > Catalog > Catalog > Layered Navigation > Price Navigation Step Calculation’ setting is ignored.
]]>
</comment>
</field>
<field id="price_filter_input" translate="label" type="select" sortOrder="100" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Show Price Slider With Input</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment>Show price slider with input.</comment>
<depends>
<field id="price_filter" separator=",">2</field>
</depends>
</field>
<field id="auto_close_sidebar" showInDefault="1" showInStore="1" showInWebsite="1" sortOrder="105" translate="label"
type="select">
<label>AutoClose Sidebar</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment>Set to AutoClose Sidebar after each filtering.</comment>
<depends>
<field id="sb_style" separator=",">1,2</field>
</depends>
</field>
<field id="rating_filter" showInDefault="1" showInStore="1" showInWebsite="1" sortOrder="110" translate="label"
type="select">
<label>Enable Rating Filter</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment>Enable/Disable Rating Filter.</comment>
<depends>
<field id="weltpixel_layerednavigation/general/enable">1</field>
</depends>
</field>
<field id="rating_filter_name" translate="label" type="text" sortOrder="115" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Rating Filter Name</label>
<comment>Rating Filter Name</comment>
<depends>
<field id="rating_filter">1</field>
</depends>
</field>
<field id="rating_filter_display" translate="label" type="select" sortOrder="120" showInDefault="1"
showInWebsite="1" showInStore="1">
<source_model>WeltPixel\LayeredNavigation\Model\Config\Source\RatingFilterDisplay</source_model>
<label>Rating Filter Display Options</label>
<comment>Rating Filter Display Options</comment>
<depends>
<field id="rating_filter">1</field>
</depends>
</field>
<field id="rating_filter_position" translate="label" type="text" sortOrder="125" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Rating Filter Position</label>
<comment>Rating Filter Position</comment>
<depends>
<field id="rating_filter">1</field>
</depends>
</field>
<field id="rating_filter_multiselect" showInDefault="1" showInStore="1" showInWebsite="1" sortOrder="130" translate="label"
type="select">
<label>Rating Filter Multiselect</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment>Is Rating Filter multiselect.</comment>
<depends>
<field id="rating_filter">1</field>
</depends>
</field>
<field id="rating_filter_counter" showInDefault="1" showInStore="1" showInWebsite="1" sortOrder="135" translate="label"
type="select">
<label>Show Rating Filter Counter</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment>Show/Hide Rating Filter counter.</comment>
<depends>
<field id="rating_filter">1</field>
</depends>
</field>
</group>
</section>
</system>
</config>
+44
View File
@@ -0,0 +1,44 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<weltpixel_layerednavigation>
<general>
<enable>1</enable>
<ajax>1</ajax>
<ajax_scroll_top>1</ajax_scroll_top>
</general>
<sidebar>
<sb_style>0</sb_style>
<allow_layered_show_hide>0</allow_layered_show_hide>
<layered_show_hide_state>open</layered_show_hide_state>
<slide_down_columns>15.66%</slide_down_columns>
<slide_down_height>450px</slide_down_height>
<filter_column_height>450px</filter_column_height>
<category_block>1</category_block>
<compare_block>1</compare_block>
<wishlist_block>1</wishlist_block>
<recentlyordered_block>1</recentlyordered_block>
<filter_button>1</filter_button>
<price_filter>1</price_filter>
<price_filter_input>0</price_filter_input>
<auto_close_sidebar>0</auto_close_sidebar>
<rating_filter>0</rating_filter>
<rating_filter_name>Rating</rating_filter_name>
<rating_filter_display>1</rating_filter_display>
<rating_filter_position>99</rating_filter_position>
<rating_filter_multiselect>0</rating_filter_multiselect>
<rating_filter_counter>0</rating_filter_counter>
<sb_selected_filters_options>1</sb_selected_filters_options>
<display_multiselect_selected_options>0</display_multiselect_selected_options>
<horizontal_box_shadow>1</horizontal_box_shadow>
</sidebar>
<attribute_display>
<filter>0</filter>
<multiselect>1</multiselect>
<qty>1</qty>
<sort>position</sort>
</attribute_display>
</weltpixel_layerednavigation>
</default>
</config>
+57
View File
@@ -0,0 +1,57 @@
<?xml version="1.0"?>
<!--
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<virtualType name="categoryFilterList" type="Magento\Catalog\Model\Layer\FilterList">
<arguments>
<argument name="filters" xsi:type="array">
<item name="attribute" xsi:type="string">WeltPixel\LayeredNavigation\Model\Layer\Filter\Attribute</item>
<item name="price" xsi:type="string">WeltPixel\LayeredNavigation\Model\Layer\Filter\Price</item>
<item name="category" xsi:type="string">WeltPixel\LayeredNavigation\Model\Layer\Filter\Category</item>
</argument>
</arguments>
</virtualType>
<virtualType name="searchFilterList" type="Magento\Catalog\Model\Layer\FilterList">
<arguments>
<argument name="filters" xsi:type="array">
<item name="attribute" xsi:type="string">WeltPixel\LayeredNavigation\Model\Layer\Filter\Attribute</item>
<item name="price" xsi:type="string">WeltPixel\LayeredNavigation\Model\Layer\Filter\Price</item>
<item name="category" xsi:type="string">WeltPixel\LayeredNavigation\Model\Layer\Filter\Category</item>
</argument>
</arguments>
</virtualType>
<preference for="Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection"
type="WeltPixel\LayeredNavigation\Model\ResourceModel\Fulltext\Collection" />
<virtualType name="Magento\CatalogSearch\Model\ResourceModel\Fulltext\CollectionFactory"
type="Magento\Catalog\Model\ResourceModel\Product\CollectionFactory">
<arguments>
<argument name="instanceName" xsi:type="string">WeltPixel\LayeredNavigation\Model\ResourceModel\Fulltext\Collection</argument>
</arguments>
</virtualType>
<virtualType name="Magento\CatalogSearch\Model\ResourceModel\Fulltext\SearchCollection"
type="WeltPixel\LayeredNavigation\Model\ResourceModel\Fulltext\Collection">
<arguments>
<argument name="searchRequestName" xsi:type="string">quick_search_container</argument>
</arguments>
</virtualType>
<!-- Since M-2.3.2 -->
<type name="Magento\Catalog\Model\Layer\Search">
<arguments>
<argument name="context" xsi:type="object">Magento\CatalogSearch\Model\Layer\Search\Context</argument>
</arguments>
</type>
<type name="Magento\Catalog\Model\Layer\Category">
<arguments>
<argument name="context" xsi:type="object">Magento\CatalogSearch\Model\Layer\Category\Context</argument>
</arguments>
</type>
<!-- End since -->
</config>
+88
View File
@@ -0,0 +1,88 @@
<?xml version="1.0"?>
<!--
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<virtualType name="WeltPixel\LayeredNavigation\Block\Navigation\Category"
type="WeltPixel\LayeredNavigation\Block\Navigation">
<arguments>
<argument name="filterList" xsi:type="object">categoryFilterList</argument>
</arguments>
</virtualType>
<virtualType name="WeltPixel\LayeredNavigation\Block\Navigation\Search"
type="WeltPixel\LayeredNavigation\Block\Navigation">
<arguments>
<argument name="filterList" xsi:type="object">searchFilterList</argument>
</arguments>
</virtualType>
<!-- @api -->
<virtualType name="Magento\LayeredNavigationStaging\Block\Navigation\Category" type="WeltPixel\LayeredNavigation\Block\Navigation">
<arguments>
<argument name="filterList" xsi:type="object">categoryFilterList</argument>
</arguments>
</virtualType>
<!-- @api -->
<virtualType name="Magento\LayeredNavigationStaging\Block\Navigation\Search" type="WeltPixel\LayeredNavigation\Block\Navigation">
<arguments>
<argument name="filterList" xsi:type="object">searchFilterList</argument>
</arguments>
</virtualType>
<preference for="Magento\LayeredNavigation\Block\Navigation\Category"
type="WeltPixel\LayeredNavigation\Block\Navigation\Category"/>
<preference for="Magento\LayeredNavigation\Block\Navigation\FilterRenderer"
type="WeltPixel\LayeredNavigation\Block\Navigation\FilterRenderer"/>
<preference for="Magento\LayeredNavigation\Block\Navigation\State"
type="WeltPixel\LayeredNavigation\Block\Navigation\State"/>
<preference for="Magento\Swatches\Block\LayeredNavigation\RenderLayered"
type="WeltPixel\LayeredNavigation\Block\LayeredNavigation\RenderLayered"/>
<preference for="Magento\Catalog\Model\ResourceModel\Layer\Filter\Attribute"
type="WeltPixel\LayeredNavigation\Model\ResourceModel\Layer\Filter\Attribute"/>
<type name="Amasty\ShopbyBrand\Controller\Index\Index">
<plugin name="WeltPixel_LayeredNavigation_Ajax_Amasty_ShopBy"
type="WeltPixel\LayeredNavigation\Plugin\Category\View"></plugin>
</type>
<type name="Magento\Catalog\Controller\Category\View">
<plugin name="WeltPixel_LayeredNavigation_Ajax_Category_View"
type="WeltPixel\LayeredNavigation\Plugin\Category\View"></plugin>
</type>
<type name="Magento\CatalogSearch\Controller\Result\Index">
<plugin name="WeltPixel_LayeredNavigation_Ajax_CategorSearch_Result"
type="WeltPixel\LayeredNavigation\Plugin\CatalogSearch\ResultView"></plugin>
</type>
<type name="Magento\Catalog\Model\Layer\FilterList">
<plugin name="WeltPixel_LayeredNavigation_Filter_List"
type="WeltPixel\LayeredNavigation\Plugin\Layer\FilterList"></plugin>
</type>
<type name="Magento\Catalog\Model\Layer\Filter\Item">
<plugin name="WeltPixel_LayeredNavigation_Item_Url"
type="WeltPixel\LayeredNavigation\Plugin\Model\Layer\Filter\Item" sortOrder="1"/>
</type>
<type name="Magento\Swatches\Block\LayeredNavigation\RenderLayered">
<plugin name="WeltPixel_LayeredNavigation_Swatches_RenderLayered"
type="WeltPixel\LayeredNavigation\Plugin\Swatches\RenderLayered" sortOrder="1"/>
</type>
<type name="Magento\Catalog\Model\Design">
<plugin name="WeltPixel_LayeredNavigation_Catalog_Design"
type="WeltPixel\LayeredNavigation\Plugin\Category\Design" sortOrder="5"/>
</type>
</config>
@@ -0,0 +1,18 @@
<?xml version="1.0"?>
<!--
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="layout_generate_blocks_after">
<observer name="remove_block" instance="WeltPixel\LayeredNavigation\Observer\RemoveBlocks"/>
</event>
<event name="controller_action_layout_render_before_catalogsearch_result_index">
<observer name="update_body_class" instance="WeltPixel\LayeredNavigation\Observer\UpdateBodyClass"/>
</event>
</config>
+17
View File
@@ -0,0 +1,17 @@
<?xml version="1.0"?>
<!--
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="WeltPixel_LayeredNavigation">
<sequence>
<module name="WeltPixel_Backend"/>
</sequence>
</module>
</config>
+119
View File
@@ -0,0 +1,119 @@
"WeltPixel Layered Navigation Properties","WeltPixel Layered Navigation Properties"
"For more settings on attribute level, go to
<strong>Stores -> Attributes -> Product -> [select desired attribute from grid] ->
Storefront Properties -> WeltPixel Layered Navigation Properties</strong>
section.","For more settings on attribute level, go to
<strong>Stores -> Attributes -> Product -> [select desired attribute from grid] ->
Storefront Properties -> WeltPixel Layered Navigation Properties</strong>
section."
"Version 1","Version 1"
"Version 2","Version 2"
"Version 3","Version 3"
Left,Left
Center,Center
"%1 and above","%1 and above"
"%1 - %2","%1 - %2"
"Something went wrong, check and test your Search Engine configurations, reindex catalog and clear cache. Thrown error: %1","Something went wrong, check and test your Search Engine configurations, reindex catalog and clear cache. Thrown error: %1"
"Bucket does not exist","Bucket does not exist"
Closed,Closed
"Fully Opened","Fully Opened"
Expandable,Expandable
"Show Attribute Options as","Show Attribute Options as"
"Can be used only with catalog input type Dropdown, Multiple Select and Price","Can be used only with catalog input type Dropdown, Multiple Select and Price"
"[Closed] option not applicable on [Slide Down] Sidebar Style. <br/> The [Closed] option is recommended if you’re using the Horizontal Design for the Layered Navigation","[Closed] option not applicable on [Slide Down] Sidebar Style. <br/> The [Closed] option is recommended if you’re using the Horizontal Design for the Layered Navigation"
"Initial Number of Visible Options","Initial Number of Visible Options"
"The number of attribute option(s) that will be initially visible. Can be used only with Show Attribute Options as - Expandable.","The number of attribute option(s) that will be initially visible. Can be used only with Show Attribute Options as - Expandable."
"The number of attribute option(s) that will be initially visible. Can be used only with Show Attribute Options as - Expandable. %1","The number of attribute option(s) that will be initially visible. Can be used only with Show Attribute Options as - Expandable. %1"
"Expandable items behaviour","Expandable items behaviour"
All,All
"Show 5 more","Show 5 more"
"Show 10 more","Show 10 more"
"Show 15 more","Show 15 more"
"Select the number of attribute option(s) to show/hide when using Expand feature.<br> Can be used only with Show Attribute Options as - Expandable.","Select the number of attribute option(s) to show/hide when using Expand feature.<br> Can be used only with Show Attribute Options as - Expandable."
"Select the number of attribute option(s) to show/hide when using Expand feature.<br> Can be used only with Show Attribute Options as - Expandable. %1","Select the number of attribute option(s) to show/hide when using Expand feature.<br> Can be used only with Show Attribute Options as - Expandable. %1"
"Enable Multiselect","Enable Multiselect"
No,No
Yes,Yes
"Allow to filter multiple options from the same attribute.","Allow to filter multiple options from the same attribute."
"Show Item Counter","Show Item Counter"
"Show item counter next to the current attribute options.","Show item counter next to the current attribute options."
"Show item counter next to the current attribute options. %1","Show item counter next to the current attribute options. %1"
"Sort By","Sort By"
Position,Position
Name,Name
"Select the sorting of the current attribute options.","Select the sorting of the current attribute options."
"Select the sorting of the current attribute options. %1","Select the sorting of the current attribute options. %1"
"Enable options filter on Desktop","Enable options filter on Desktop"
"Enable search functionality for attribute options on desktop.","Enable search functionality for attribute options on desktop."
"Enable search functionality for attribute options on desktop. %1","Enable search functionality for attribute options on desktop. %1"
"Enable options filter on Mobile","Enable options filter on Mobile"
"Enable search functionality for attribute options on mobile.","Enable search functionality for attribute options on mobile."
"Enable search functionality for attribute options on mobile. %1","Enable search functionality for attribute options on mobile. %1"
"Category Visibility","Category Visibility"
"Visible in all categories","Visible in all categories"
"Visible only in the following categories","Visible only in the following categories"
"Not visible in the following categories","Not visible in the following categories"
"Select visibility behaviour in categories for the current attribute.","Select visibility behaviour in categories for the current attribute."
"Select Categories","Select Categories"
"Select categories.","Select categories."
text,text
"Search for options ...","Search for options ..."
item,item
items,items
Price:,Price:
Apply,Apply
"Now Shopping by","Now Shopping by"
Previous,Previous
Remove,Remove
"Remove This Item","Remove This Item"
"Shop By","Shop By"
"Clear All","Clear All"
"Shopping Options","Shopping Options"
"Show Filters","Show Filters"
"Hide Filters","Hide Filters"
"Layered Navigation Pro","Layered Navigation Pro"
"General Settings","General Settings"
"Enable Layered Navigation","Enable Layered Navigation"
"Enable Ajax","Enable Ajax"
"Scroll to top after Ajax load","Scroll to top after Ajax load"
"Sidebar Settings","Sidebar Settings"
"Sidebar Style","Sidebar Style"
"Columns No.","Columns No."
"Horizontal Design Version","Horizontal Design Version"
"Filter Alignment","Filter Alignment"
"Enable Sticky Filters","Enable Sticky Filters"
"Display Selected Filters","Display Selected Filters"
"If set to ""Yes"", filters that have been selected will be displayed under the Layered Navigation. </br>
If set to ""No"", the user will not see the filters they select, and only a ""Clear All"" button will be shown.","If set to ""Yes"", filters that have been selected will be displayed under the Layered Navigation. </br>
If set to ""No"", the user will not see the filters they select, and only a ""Clear All"" button will be shown."
"Display Multiselect Attributes Selected Options Counter","Display Multiselect Attributes Selected Options Counter"
"Filter Box Height","Filter Box Height"
"Box Shadow","Box Shadow"
"Enable to display a shadow for the Layered Navigation Slide Down box.","Enable to display a shadow for the Layered Navigation Slide Down box."
"Filter Button Color","Filter Button Color"
"Filter Button Text Color","Filter Button Text Color"
"Filter Button Hover Color","Filter Button Hover Color"
"Filter Button Hover Text Color","Filter Button Hover Text Color"
Border,Border
"Border Color","Border Color"
"Border Radius","Border Radius"
"Filter Column Height","Filter Column Height"
"Allow customer to show/hide Layered Navigation","Allow customer to show/hide Layered Navigation"
"Filters default state","Filters default state"
"Show Compare Products block","Show Compare Products block"
"Show/Hide Compare Products block from Sidebar Style - Default.","Show/Hide Compare Products block from Sidebar Style - Default."
"Show Wish List block","Show Wish List block"
"Show/Hide Wish List block from Sidebar Style - Default.","Show/Hide Wish List block from Sidebar Style - Default."
"Show Recently Ordered block","Show Recently Ordered block"
"Show/Hide Recently Ordered block from Sidebar Style - Default.","Show/Hide Recently Ordered block from Sidebar Style - Default."
"Show Category Filter","Show Category Filter"
"Filter Button","Filter Button"
"Price Filter","Price Filter"
"Show Price Slider With Input","Show Price Slider With Input"
"AutoClose Sidebar","AutoClose Sidebar"
"Enable Rating Filter","Enable Rating Filter"
"Rating Filter Name","Rating Filter Name"
"Rating Filter Display Options","Rating Filter Display Options"
"Rating Filter Position","Rating Filter Position"
"Rating Filter Multiselect","Rating Filter Multiselect"
"Show Rating Filter Counter","Show Rating Filter Counter"
1 WeltPixel Layered Navigation Properties WeltPixel Layered Navigation Properties
2 For more settings on attribute level, go to <strong>Stores -> Attributes -> Product -> [select desired attribute from grid] -> Storefront Properties -> WeltPixel Layered Navigation Properties</strong> section. For more settings on attribute level, go to <strong>Stores -> Attributes -> Product -> [select desired attribute from grid] -> Storefront Properties -> WeltPixel Layered Navigation Properties</strong> section.
3 Version 1 Version 1
4 Version 2 Version 2
5 Version 3 Version 3
6 Left Left
7 Center Center
8 %1 and above %1 and above
9 %1 - %2 %1 - %2
10 Something went wrong, check and test your Search Engine configurations, reindex catalog and clear cache. Thrown error: %1 Something went wrong, check and test your Search Engine configurations, reindex catalog and clear cache. Thrown error: %1
11 Bucket does not exist Bucket does not exist
12 Closed Closed
13 Fully Opened Fully Opened
14 Expandable Expandable
15 Show Attribute Options as Show Attribute Options as
16 Can be used only with catalog input type Dropdown, Multiple Select and Price Can be used only with catalog input type Dropdown, Multiple Select and Price
17 [Closed] option not applicable on [Slide Down] Sidebar Style. <br/> The [Closed] option is recommended if you’re using the Horizontal Design for the Layered Navigation [Closed] option not applicable on [Slide Down] Sidebar Style. <br/> The [Closed] option is recommended if you’re using the Horizontal Design for the Layered Navigation
18 Initial Number of Visible Options Initial Number of Visible Options
19 The number of attribute option(s) that will be initially visible. Can be used only with Show Attribute Options as - Expandable. The number of attribute option(s) that will be initially visible. Can be used only with Show Attribute Options as - Expandable.
20 The number of attribute option(s) that will be initially visible. Can be used only with Show Attribute Options as - Expandable. %1 The number of attribute option(s) that will be initially visible. Can be used only with Show Attribute Options as - Expandable. %1
21 Expandable items behaviour Expandable items behaviour
22 All All
23 Show 5 more Show 5 more
24 Show 10 more Show 10 more
25 Show 15 more Show 15 more
26 Select the number of attribute option(s) to show/hide when using Expand feature.<br> Can be used only with Show Attribute Options as - Expandable. Select the number of attribute option(s) to show/hide when using Expand feature.<br> Can be used only with Show Attribute Options as - Expandable.
27 Select the number of attribute option(s) to show/hide when using Expand feature.<br> Can be used only with Show Attribute Options as - Expandable. %1 Select the number of attribute option(s) to show/hide when using Expand feature.<br> Can be used only with Show Attribute Options as - Expandable. %1
28 Enable Multiselect Enable Multiselect
29 No No
30 Yes Yes
31 Allow to filter multiple options from the same attribute. Allow to filter multiple options from the same attribute.
32 Show Item Counter Show Item Counter
33 Show item counter next to the current attribute options. Show item counter next to the current attribute options.
34 Show item counter next to the current attribute options. %1 Show item counter next to the current attribute options. %1
35 Sort By Sort By
36 Position Position
37 Name Name
38 Select the sorting of the current attribute options. Select the sorting of the current attribute options.
39 Select the sorting of the current attribute options. %1 Select the sorting of the current attribute options. %1
40 Enable options filter on Desktop Enable options filter on Desktop
41 Enable search functionality for attribute options on desktop. Enable search functionality for attribute options on desktop.
42 Enable search functionality for attribute options on desktop. %1 Enable search functionality for attribute options on desktop. %1
43 Enable options filter on Mobile Enable options filter on Mobile
44 Enable search functionality for attribute options on mobile. Enable search functionality for attribute options on mobile.
45 Enable search functionality for attribute options on mobile. %1 Enable search functionality for attribute options on mobile. %1
46 Category Visibility Category Visibility
47 Visible in all categories Visible in all categories
48 Visible only in the following categories Visible only in the following categories
49 Not visible in the following categories Not visible in the following categories
50 Select visibility behaviour in categories for the current attribute. Select visibility behaviour in categories for the current attribute.
51 Select Categories Select Categories
52 Select categories. Select categories.
53 text text
54 Search for options ... Search for options ...
55 item item
56 items items
57 Price: Price:
58 Apply Apply
59 Now Shopping by Now Shopping by
60 Previous Previous
61 Remove Remove
62 Remove This Item Remove This Item
63 Shop By Shop By
64 Clear All Clear All
65 Shopping Options Shopping Options
66 Show Filters Show Filters
67 Hide Filters Hide Filters
68 Layered Navigation Pro Layered Navigation Pro
69 General Settings General Settings
70 Enable Layered Navigation Enable Layered Navigation
71 Enable Ajax Enable Ajax
72 Scroll to top after Ajax load Scroll to top after Ajax load
73 Sidebar Settings Sidebar Settings
74 Sidebar Style Sidebar Style
75 Columns No. Columns No.
76 Horizontal Design Version Horizontal Design Version
77 Filter Alignment Filter Alignment
78 Enable Sticky Filters Enable Sticky Filters
79 Display Selected Filters Display Selected Filters
80 If set to "Yes", filters that have been selected will be displayed under the Layered Navigation. </br> If set to "No", the user will not see the filters they select, and only a "Clear All" button will be shown. If set to "Yes", filters that have been selected will be displayed under the Layered Navigation. </br> If set to "No", the user will not see the filters they select, and only a "Clear All" button will be shown.
81 Display Multiselect Attributes Selected Options Counter Display Multiselect Attributes Selected Options Counter
82 Filter Box Height Filter Box Height
83 Box Shadow Box Shadow
84 Enable to display a shadow for the Layered Navigation Slide Down box. Enable to display a shadow for the Layered Navigation Slide Down box.
85 Filter Button Color Filter Button Color
86 Filter Button Text Color Filter Button Text Color
87 Filter Button Hover Color Filter Button Hover Color
88 Filter Button Hover Text Color Filter Button Hover Text Color
89 Border Border
90 Border Color Border Color
91 Border Radius Border Radius
92 Filter Column Height Filter Column Height
93 Allow customer to show/hide Layered Navigation Allow customer to show/hide Layered Navigation
94 Filters default state Filters default state
95 Show Compare Products block Show Compare Products block
96 Show/Hide Compare Products block from Sidebar Style - Default. Show/Hide Compare Products block from Sidebar Style - Default.
97 Show Wish List block Show Wish List block
98 Show/Hide Wish List block from Sidebar Style - Default. Show/Hide Wish List block from Sidebar Style - Default.
99 Show Recently Ordered block Show Recently Ordered block
100 Show/Hide Recently Ordered block from Sidebar Style - Default. Show/Hide Recently Ordered block from Sidebar Style - Default.
101 Show Category Filter Show Category Filter
102 Filter Button Filter Button
103 Price Filter Price Filter
104 Show Price Slider With Input Show Price Slider With Input
105 AutoClose Sidebar AutoClose Sidebar
106 Enable Rating Filter Enable Rating Filter
107 Rating Filter Name Rating Filter Name
108 Rating Filter Display Options Rating Filter Display Options
109 Rating Filter Position Rating Filter Position
110 Rating Filter Multiselect Rating Filter Multiselect
111 Show Rating Filter Counter Show Rating Filter Counter
+7
View File
@@ -0,0 +1,7 @@
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'WeltPixel_LayeredNavigation',
__DIR__
);
@@ -0,0 +1,12 @@
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock name="attribute_edit_tabs">
<action method="addTabAfter">
<argument name="name" xsi:type="string">weltpixellayerednavigation</argument>
<argument name="block" xsi:type="string">WeltPixel\LayeredNavigation\Block\Adminhtml\Product\Attribute\Edit\Tab\Options</argument>
<argument name="after" xsi:type="string">front</argument>
</action>
</referenceBlock>
</body>
</page>
@@ -0,0 +1,16 @@
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
</head>
<body>
<referenceContainer name="before.body.end">
<block
ifconfig="weltpixel_layerednavigation/general/enable"
class="WeltPixel\LayeredNavigation\Block\LayeredNavigationAdd"
name="layerednavigationadd"
template="WeltPixel_LayeredNavigation::layerednavigationadd.phtml"
/>
</referenceContainer>
</body>
</page>
@@ -0,0 +1,50 @@
<?xml version="1.0"?>
<!--
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<attribute name="class" value="wp-ln-filter-page"/>
<referenceBlock name="catalog.leftnav">
<action method="setTemplate" ifconfig="weltpixel_layerednavigation/general/enable">
<argument name="template" xsi:type="string">WeltPixel_LayeredNavigation::layer/view.phtml</argument>
</action>
<container name="layer.additional.info" as="layer_additional_info"/>
<container name="layer.content.before" as="layer_content_before"/>
</referenceBlock>
<referenceBlock name="catalog.navigation.renderer">
<action method="setTemplate" ifconfig="weltpixel_layerednavigation/general/enable">
<argument name="template" xsi:type="string">WeltPixel_LayeredNavigation::layer/filter.phtml</argument>
</action>
</referenceBlock>
<referenceContainer name="content">
<block class="Magento\Framework\View\Element\Template" name="layer.category.products" template="WeltPixel_LayeredNavigation::products.phtml" />
</referenceContainer>
<referenceContainer name="columns">
<block
ifconfig="weltpixel_layerednavigation/sidebar/allow_layered_show_hide"
class="Magento\Framework\View\Element\Template"
name="wp-show-hide-desktop-filter"
template="WeltPixel_LayeredNavigation::showhide_desktop_filter.phtml"
before="main"
/>
</referenceContainer>
<move element="category.products" destination="layer.category.products"/>
<referenceContainer name="before.body.end">
<block
ifconfig="weltpixel_layerednavigation/general/enable"
class="WeltPixel\LayeredNavigation\Block\LayeredNavigationAdd"
name="layerednavigationadd"
template="WeltPixel_LayeredNavigation::layerednavigationadd.phtml"
/>
</referenceContainer>
</body>
</page>
@@ -0,0 +1,13 @@
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<attribute name="class" value="weltpixel-horizontalnavigation"/>
<referenceContainer name="before.body.end">
<block
class="Magento\Framework\View\Element\Template"
name="horizontalnavigation.js"
template="WeltPixel_LayeredNavigation::horizontalnavigation.phtml"
/>
</referenceContainer>
</body>
</page>
@@ -0,0 +1,37 @@
<?xml version="1.0"?>
<!--
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<attribute name="class" value="page-products"/>
<referenceContainer name="sidebar.main">
<block class="WeltPixel\LayeredNavigation\Block\Navigation\Search" name="catalogsearch.leftnav" before="-" template="WeltPixel_LayeredNavigation::layer/view.phtml">
<block class="WeltPixel\LayeredNavigation\Block\Navigation\State" name="catalogsearch.navigation.state" as="state" />
<block class="WeltPixel\LayeredNavigation\Block\Navigation\FilterRenderer" name="catalogsearch.navigation.renderer" as="renderer" template="WeltPixel_LayeredNavigation::layer/filter.phtml"/>
</block>
</referenceContainer>
<referenceContainer name="content">
<block class="Magento\Framework\View\Element\Template" name="wp.layer.search.result" template="WeltPixel_LayeredNavigation::search_products.phtml" />
</referenceContainer>
<move element="search.result" destination="wp.layer.search.result"/>
<referenceContainer name="before.body.end">
<block
ifconfig="weltpixel_layerednavigation/general/enable"
class="WeltPixel\LayeredNavigation\Block\LayeredNavigationAdd"
name="layerednavigationadd"
template="WeltPixel_LayeredNavigation::layerednavigationadd.phtml"
/>
</referenceContainer>
</body>
</page>
@@ -0,0 +1,14 @@
var config = {
map: {
'*': {
wpFilterSelect: 'WeltPixel_LayeredNavigation/js/wpFilterSelect',
wpShowMoreLess: 'WeltPixel_LayeredNavigation/js/wpShowMoreLess',
wpInstantSearch: 'WeltPixel_LayeredNavigation/js/wpInstantSearch',
jqueryTouch: 'WeltPixel_LayeredNavigation/js/jqueryUiTouch'
}
},
shim: {
jqueryTouch: ['jquery', 'jquery-ui-modules/mouse', 'jquery-ui-modules/widget', 'jquery/validate']
}
};
@@ -0,0 +1,17 @@
<script>
require([
"jquery",
], function($){
$(document).ready(function () {
$(document).on('click', '.filter-options-item .filter-options-title', function() {
var that = this;
$('.filter-options-item.active > .filter-options-title').each(function(key, value) {
if (that != value) {
$(value).parent().removeClass('active');
}
});
});
});
});
</script>
@@ -0,0 +1,65 @@
<?php
// @codingStandardsIgnoreFile
?>
<?php $attributeId = $block->getAttributeId()?>
<?php $isMulti = $block->getIsMultiselect()?>
<?php $canShowQty = (is_null($block->getShowQty())) ? $this->helper('\Magento\Catalog\Helper\Data')->shouldDisplayProductCountOnLayer() : $block->getShowQty();?>
<?php $canShowInstantSearch = $block->canShowInstantSearch() ? 'desktop' : ''?>
<?php $canShowInstantSearchMobile = $block->canShowInstantSearchMobile() ? 'mobile' : ''?>
<?php $categoryParamLabel = $block->getCategoryParamLabel()?>
<?php $ratingParamLabel = $block->getRatingParamLabel()?>
<?php
$listItemStyle = 'display: none';
if ($attributeId == \WeltPixel\LayeredNavigation\Helper\Data::RATING_PARAM_LABEL) {
$listItemStyle = '';
}
?>
<div class="wp-instant-search-wrapper <?= $block->escapeHtmlAttr($canShowInstantSearchMobile) ?> <?= $block->escapeHtmlAttr($canShowInstantSearch) ?>">
<input type="text" class="wp-instant-search-inp" id="instant_search_<?= $block->escapeHtmlAttr($attributeId) ?>" data-attr-id="<?= $block->escapeHtmlAttr($attributeId) ?>" placeholder="<?= $block->escapeHtmlAttr(__('Search for options ...')) ?>">
</div>
<ol class="items" id="<?= $block->escapeHtmlAttr($attributeId) ?>_items" >
<?php foreach ($filterItems as $filterItem): ?>
<?php $requestVar = $filterItem->getFilter()->getRequestVar();?>
<?php $filterItemVal = is_array($filterItem->getValue()) ? implode('-', $filterItem->getValue()) : $filterItem->getValue()?>
<?php $idAddOn = $attributeId?>
<?php if($requestVar == $categoryParamLabel):?>
<?php $dataOptPath = $categoryParamLabel.'='.$filterItemVal;?>
<?php elseif($requestVar == $ratingParamLabel):?>
<?php $dataOptPath = $ratingParamLabel.'='.$filterItemVal;?>
<?php $idAddOn = $ratingParamLabel?>
<?php else:?>
<?php $dataOptPath = $filterItem->getFilter()->getAttributeModel()->getAttributeCode().'='. $filterItemVal;?>
<?php endif;?>
<li class="item" style="<?= $block->escapeHtmlAttr($listItemStyle) ?>" id="wp_ln_attr_<?= $block->escapeHtmlAttr($idAddOn) ?>_<?= $block->escapeHtmlAttr(is_array($filterItem->getValue()) ? implode('-', $filterItem->getValue()) : $filterItem->getValue()) ?>">
<?php if ($filterItem->getCount() > 0): $filter = $filterItem->getFilter();?>
<a href="<?= $block->escapeUrl($filterItem->getUrl()) ?>"
data-opt-path="<?= $block->escapeHtmlAttr($dataOptPath) ?>"
data-is-multi="<?= /* @noEscape */ $isMulti ?>">
<?= /* @noEscape */ $filterItem->getLabel() ?>
<?php if ($canShowQty): ?>
<span class="count"><?= /* @noEscape */ $filterItem->getCount() ?><span class="filter-count-label">
<?php if ($filterItem->getCount() == 1):?> <?= /* @noEscape */ __('item') ?><?php else:?> <?= /* @noEscape */ __('items') ?><?php endif;?></span></span>
<?php endif; ?>
</a>
<?php else:?>
<a href="#" class="wp-filter-disabled" disabled="disabled"><?= /* @noEscape */ $filterItem->getLabel() ?></a>
<?php if ($canShowQty): ?>
<span class="count"><?= /* @noEscape */ $filterItem->getCount() ?><span class="filter-count-label">
<?php if ($filterItem->getCount() == 1):?><?= /* @noEscape */ __('item') ?><?php else:?><?= /* @noEscape */ __('items') ?><?php endif;?></span></span>
<?php endif; ?>
<?php endif; ?>
</li>
<?php endforeach ?>
<?php if($requestVar != $ratingParamLabel):?>
<div class="wp-ln-actions" data-visibleItems="<?= /* @noEscape */ (int) $block->getVisibleItems() ?>" data-visibleItemsStep="<?= /* @noEscape */ (int) $block->getVisibleItemsStep() ?>" data-attrId="<?= $block->escapeHtmlAttr($attributeId) ?>">
<b id="showLess_<?= /* @noEscape */ $attributeId?>" class="wp-ln-action wp-ln-show-less icon-line-arrow-up"></b>
<b id="loadMore_<?= /* @noEscape */ $attributeId?>" class="wp-ln-action wp-ln-load-more icon-line-arrow-down"></b>
</div>
<?php endif;?>
</ol>
@@ -0,0 +1,134 @@
<?php $priceData = $this->getPriceConfigData()?>
<?php $priceIsInputType = $this->priceIsInputType()?>
<div id="slider-range"></div>
<div class="wp-slider-inp">
<div class="wp-slider-inp-range">
<?php if($priceIsInputType): ?>
<input type="text" id="amount_from" class="wp-price-slider-inp inp-type" />
<?php else : ?>
<label for="amount"><?= $block->escapeHtml(__('Price:'))?></label>
<div class="price-value-wrapper">
<span class="wp-slider-currency"><?= $block->escapeHtml($priceData['currency']) ?></span>
<span id="amount_from" class="wp-price-slider-inp"></span>
<?php endif;?>
<span class="wp-slider-range-separator">-</span>
<?php if($priceIsInputType): ?>
<input type="text" id="amount_to" class="wp-price-slider-inp inp-type" />
<?php else : ?>
<span class="wp-slider-currency"><?= $block->escapeHtml($priceData['currency']) ?></span>
<span id="amount_to" class="wp-price-slider-inp"></span>
</div>
<?php endif;?>
<a href="<?= $block->escapeUrl($this->getSliderApplyUrl()) ?>" class="wp-price-slider-a" id="wp_ln_price_slider"><?= $block->escapeHtml(__('Apply')) ?></a>
</div>
</div>
<script>
require(['jquery','jquery-ui-modules/effect-slide','jquery-ui-modules/mouse','jquery-ui-modules/widget','<?= $block->escapeJs($block->getSliderJsWidget()) ?>','jqueryTouch'], function($){
$( function() {
var priceIsInputType = <?= $priceIsInputType ? 'true': 'false'?>;
var priceSearchArr = getPriceParam();
var priceSearchMinInp = (priceSearchArr) ? priceSearchArr[0] : <?= /* @noEscape */ $priceData['min']?>;
var priceSearchMaxInp = (priceSearchArr) ? priceSearchArr[1] : <?= /* @noEscape */ $priceData['max']?>;
$("#slider-range").slider({
range: true,
min: <?= /* @noEscape */ $priceData['minX']?>,
max: <?= /* @noEscape */ $priceData['maxX']?>,
step: <?= /* @noEscape */ $priceData['step']?>,
values: [ priceSearchMinInp , priceSearchMaxInp ],
slide: function( event, ui ) {
if(priceIsInputType) {
$("#amount_from").val(ui.values[0]);
$("#amount_to").val(ui.values[1]);
} else {
$("#amount_from").text(ui.values[0]);
$("#amount_to").text(ui.values[1]);
}
var priceParam = 'price=' + ui.values[0] + '-' + ui.values[1],
link = window.location.href,
cleanLink = removeParam('price', removeParam('p', link)),
sliderLink = cleanLink + getSeparator(cleanLink) +priceParam;
$('#wp_ln_price_slider').attr('href', sliderLink);
}
});
if(priceIsInputType) {
$("#amount_from" ).val($( "#slider-range" ).slider( "values", 0 ));
$('#amount_to').val($( "#slider-range" ).slider( "values", 1 ));
} else {
$("#amount_from" ).text($( "#slider-range" ).slider( "values", 0 ));
$('#amount_to').text($( "#slider-range" ).slider( "values", 1 ));
}
$('.wp-price-slider-inp').on('keyup', function() {
var minPrice = (priceIsInputType) ? $("#amount_from" ).val() : $("#amount_from" ).text(),
maxPrice = (priceIsInputType) ? $("#amount_to" ).val() :$("#amount_to" ).text(),
cleanLink = removeParam('price', removeParam('p', window.location.href)),
priceParam = 'price=' + minPrice + '-' + maxPrice,
sliderLink = cleanLink + getSeparator(cleanLink) + priceParam;
$('#wp_ln_price_slider').attr('href', sliderLink);
});
/** get parameter separator from link*/
function getSeparator(link) {
var sep = link.indexOf('?');
if(sep !== -1) {
return '&';
}
return '?';
}
/** remove existing 'price' parameter from url */
function removeParam(key, url) {
if (!url) url = window.location.href;
var hashParts = url.split('#'),
regex = new RegExp("([?&])" + key + "=.*?(&|#|$)", "i");
if (hashParts[0].match(regex)) {
url = hashParts[0].replace(regex, '$1');
url = url.replace(/([?&])$/, '');
if (typeof hashParts[1] !== 'undefined' && hashParts[1] !== null)
url += '#' + hashParts[1];
}
return url;
}
/** get 'price' parameter value from link */
function getPriceParam() {
var priceArr = false;
var params = parseQueryString();
var price = params['price'];
if(price) {
var priceArr = price.split("-");
}
return priceArr;
}
function parseQueryString(){
var str = window.location.search;
var objURL = {};
str.replace(
new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
function( $0, $1, $2, $3 ){
objURL[ $1 ] = $3;
}
);
return objURL;
}
});
});
</script>
@@ -0,0 +1,65 @@
<?php
// @codingStandardsIgnoreFile
?>
<?php
/**
* Category layered navigation state
*
* @var $block \WeltPixel\LayeredNavigation\Block\Navigation\State
*/
?>
<?php $_filters = $block->getActiveFilters() ?>
<?php $categoryParamLabel = $block->getCategoryParamLabel()?>
<?php $ratingParamLabel = $block->getRatingParamLabel()?>
<?php if (!empty($_filters)): ?>
<div id="wp_ln_shopby" class="filter-current" data-mage-init='{"collapsible":{"openedState": "active", "collapsible": true, "active": true }}'>
<strong class="block-subtitle filter-current-subtitle"
role="heading"
data-role="title"
aria-level="2"
data-count="<?= /* @noEscape */ count($_filters) ?>"><?= $block->escapeHtml(__('Now Shopping by')) ?>
</strong>
<div class="items" id="wp_ln_shopby_items" data-role="content">
<?php foreach ($_filters as $_filter): ?>
<?php
$requestVar = $_filter->getFilter()->getRequestVar();
$filterItemVal = (is_array($_filter->getValue())) ? implode('-', $_filter->getValue()) : $_filter->getValue();
if ($requestVar == $categoryParamLabel) {
$dataAttrId = '0_' . $filterItemVal;
$filterLabel = $block->stripTags($_filter->getLabel());
} elseif ($requestVar == $ratingParamLabel) {
$dataAttrId = $ratingParamLabel . '_' . $filterItemVal;
$filterLabel = $block->getRateFilterLabel($_filter);
} else {
$dataAttrId = $_filter->getFilter()->getAttributeModel()->getAttributeId() . '_' . $filterItemVal;
$filterLabel = $block->stripTags($_filter->getLabel());
}
?>
<li class="item" data-attr-id="<?= $block->escapeHtmlAttr($dataAttrId) ?>">
<span class="filter-label"><?= $block->escapeHtml(__($_filter->getName())) ?></span>
<span class="filter-value"><?= $block->escapeHtml($filterLabel) ?></span>
<?php
$clearLinkUrl = $_filter->getClearLinkUrl();
$currentFilterName = $block->escapeHtml(__($_filter->getName())) . " " . $block->stripTags($_filter->getLabel());
if ($clearLinkUrl):
?>
<a class="action previous" href="<?= $block->escapeUrl($_filter->getRemoveUrl()) ?>"
title="<?= $block->escapeHtmlAttr(__('Previous')) ?>">
<span><?= $block->escapeHtml(__('Previous')) ?></span>
</a>
<a class="action remove"
title="<?= $block->escapeHtmlAttr($_filter->getFilter()->getClearLinkText()) ?>"
href="<?= $block->escapeUrl($clearLinkUrl) ?>">
<span><?= $block->escapeHtml($_filter->getFilter()->getClearLinkText()) ?></span>
</a>
<?php else: ?>
<a class="action remove" href="<?= $block->escapeUrl($_filter->getRemoveUrl()) ?>"
title="<?= $block->escapeHtmlAttr(__('Remove') . ' ' . $currentFilterName) ?>">
<span><?= $block->escapeHtml(__('Remove This Item')) ?></span>
</a>
<?php endif; ?>
</li>
<?php endforeach; ?>
</div>
</div>
<?php endif; ?>
@@ -0,0 +1,279 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
?>
<?php
/**
* Category layered navigation
*
* @var $block WeltPixel\LayeredNavigation\Block\Navigation
*/
$_helper = $this->helper('\WeltPixel\LayeredNavigation\Helper\Data');
$isAjaxMode = $block->isAjaxMode();
$isAutoClose = $block->isAutoClose();
$isAjaxScrollToTopClass = ($block->isAjaxScrollToTop()) ? 'ajax-scroll-top' : '';
$isAutoCloseClass = ($isAutoClose) ? 'auto-close' : 'manual-close';
$jsClass = ($isAjaxMode) ? 'WeltPixel_LayeredNavigation/js/product/list/toolbar' : false;
/* Horizontal Sidebar Design Settings */
$sidebarStyle = $_helper->getSidebarStyle();
$selectedFilters = $_helper->getSelectedFiltersOptions();
$horizontalBoxShadow = $_helper->getHorizontalBoxShadow();
$horizontalSbDesignVersion = ($sidebarStyle === '3' ? $_helper->getHorizontalSidebarDesignVersion() : '');
$filterPosition = ($horizontalSbDesignVersion === 'v2' ? $_helper->getHorizontalSidebarFilterPosition() : '');
$reverseOrderClass = ($horizontalSbDesignVersion === 'v2' ? 'reverse-order' : '');
$horizontalDesignClass = ($horizontalSbDesignVersion === '' ? '' : 'horizontal-' . $horizontalSbDesignVersion);
$filterAlignmentClass = ($horizontalSbDesignVersion === 'v2' ? 'filter-align-' . $filterPosition : '');
$selectedFiltersClass = ($selectedFilters === '1' ? 'show-selected-filters' : 'hide-selected-filters');
$horizontalBoxShadowClass = ($sidebarStyle === '2' && $horizontalBoxShadow === '1' ? '' : 'no-box-shadow');
/* Horizontal Sidebar Design V3 Settings */
$filtersBorder = ($_helper->getHorizontalFiltersBorder() ? $_helper->getHorizontalFiltersBorder() : '');
$filtersBorderRadius = ($_helper->getHorizontalFiltersBorderRadius() ? $_helper->getHorizontalFiltersBorderRadius() : '');
$filterButtonColor = ($horizontalSbDesignVersion === 'v3' ? $_helper->getHorizontalV3FiltersButtonColor() : '');
$filterTextColor = ($horizontalSbDesignVersion === 'v3' ? $_helper->getHorizontalV3FiltersTextColor() : '');
$filterButtonHoverColor = ($horizontalSbDesignVersion === 'v3' ? $_helper->getHorizontalV3FiltersButtonHoverColor() : '');
$filterTextHoverColor = ($horizontalSbDesignVersion === 'v3' ? $_helper->getHorizontalV3FiltersTextHoverColor() : '');
$filtersBorderColor = ($_helper->getHorizontalFiltersBorderColor() ? $_helper->getHorizontalFiltersBorderColor() : '');
$isMultiSelectOptionDisplayEnabled = $_helper->displayMultiselectAttributeSelectedOptions();
/* Sticky Filters */
$mobileBreakpoint = ($_helper->getMobileThreshold() === '' ? '768' : $_helper->getMobileThreshold());
$isStickyFiltersEnabled = ($horizontalSbDesignVersion === 'v2' ? $_helper->isHorizontalSidebarStickyEnabled() : '0');
?>
<div class="wp-filters <?php if ($isAjaxMode) echo 'wp-filters-ajax' ?>">
<?= /* @noEscape */
$block->getFilterButtonHtml() ?>
</div>
<?php if ($block->canShowBlock()): ?>
<div class="block filter <?= $block->escapeHtmlAttr($isAjaxScrollToTopClass) ?> <?= $block->escapeHtmlAttr($horizontalBoxShadowClass) ?> <?= $block->escapeHtmlAttr($isAutoCloseClass) ?> <?= $block->escapeHtmlAttr($horizontalDesignClass) ?> <?= $block->escapeHtmlAttr($filterAlignmentClass) ?> <?= $block->escapeHtmlAttr($selectedFiltersClass) ?>" id="layered-filter-block"
data-mage-init='<?= /* @noEscape */ json_encode(["collapsible"=>["openedState"=>"active","collapsible"=>true,"active"=>false,"collateral"=>["openedState"=>"filter-active","element"=>"body"]]]) ?>'>
<?php $filtered = count($block->getLayer()->getState()->getFilters()) ?>
<div class="block-title filter-title" data-count="<?= /* @noEscape */
$filtered ?>">
<strong data-role="title"><?= /* @noEscape */
__('Shop By') ?></strong>
</div>
<div class="block-content filter-content <?= /* @noEscape */ $reverseOrderClass ?>">
<?php if ($horizontalSbDesignVersion === 'v2') : ?>
<div class="filter-actions-wrapper">
<?php endif; ?>
<?= $block->getChildHtml('state') ?>
<?php if ($block->getLayer()->getState()->getFilters()): ?>
<div class="block-actions filter-actions">
<a href="<?= $block->escapeUrl($block->getClearUrl()) ?>" class="action clear filter-clear"><span><?= $block->escapeHtml(__('Clear All')) ?></span></a>
</div>
<?php endif; ?>
<?php if ($horizontalSbDesignVersion === 'v2') : ?>
</div>
<?php endif; ?>
<?php $activeFilters = $block->getActiveFilters() ?>
<?php $wrapOptions = false; ?>
<?php foreach ($block->getFilters() as $k => $filter): ?>
<?php $filterAttributeId = $filter->getData('attribute_model') ? $filter->getData('attribute_model')->getAttributeId() : 0; ?>
<?php $attributeId = (!$block->isCategoryFilter($filter) && !$block->isRatingFilter($filter)) ? $filterAttributeId : 0; ?>
<?php $categoryVisibility = $this->getCategoryVisibility($attributeId)?>
<?php if ($filter->getItemsCount() && $categoryVisibility): ?>
<?php if (!$wrapOptions): ?>
<strong role="heading" aria-level="2" class="block-subtitle filter-subtitle"><?= /* @noEscape */
__('Shopping Options') ?></strong>
<div class="filter-options" id="narrow-by-list" data-role="content"
data-mage-init='{"accordion":{"openedState": "active", "collapsible": true, "active": "<?php /* @noEscape */ echo $activeFilters; ?>", "multipleCollapsible": true, "animate":{ "duration" :300, "easing":"easeOutCubic"}}}'>
<?php $wrapOptions = true; ?>
<?php endif; ?>
<div data-role="collapsible" class="filter-options-item">
<?php $block->getChildBlock('renderer')->setAttributeId($filter) ?>
<div data-role="title" class="filter-options-title">
<?= $block->escapeHtml(__($filter->getName())) ?>
<?php if ($isMultiSelectOptionDisplayEnabled && $filter->getSelectedOptionsCounter() > 0) : ?>
<span class="ms_counter">(<?= /* @noEscape */ $filter->getSelectedOptionsCounter() ?>)</span>
<?php endif; ?>
</div>
<div id="attr_<?php /* @noEscape */ echo $attributeId ?>" data-role="content"
class="filter-options-content">
<?php if ($horizontalSbDesignVersion === 'v3'):?>
<div class="filter-options-content-title"> <?= $block->escapeHtml(__($filter->getName())) ?></div>
<?php endif;?>
<?= /* @noEscape */ $block->getChildBlock('renderer')->render($filter) ?></div>
</div>
<?php endif; ?>
<?php endforeach; ?>
<?php if ($wrapOptions): ?>
</div>
<?php else: ?>
<script>
require([
'jquery'
], function ($) {
$('#layered-filter-block').addClass('filter-no-options');
});
</script>
<?php endif; ?>
</div>
</div>
<?php endif; ?>
<div class="wp-ln-overlay"></div>
<div class="wp-ln-slider-js" data-mage-init='<?= /* @noEscape */ $block->getWidgetOptionsJson() ?>'>
<script>
require(['jquery', 'jquery-ui-modules/effect-slide'], function($) {
if ($('body').hasClass('slider-layer')) {
$('body.slider-layer #layered-filter-block').addClass('slide-in-filter');
}
if ($('body').hasClass('slider-down-layer') && $(window).width() >= <?php /* @noEscape */ echo $mobileBreakpoint ?>) {
var noOfColumns = '<?= $block->escapeJs($block->noOfColumns()) ?>',
boxHeight = '<?= $block->escapeJs($block->boxHeight()) ?>',
filterHeight = '<?= $block->escapeJs($block->filterColumnHeight()) ?>',
productWrapperMarginTop = (parseInt(boxHeight.substring(0, boxHeight.length - 2)) + 50) + 'px';
$('body.slider-down-layer #layered-filter-block').addClass('slide-down-filter');
$('body.slider-down-layer .slide-down-filter').css({'height':boxHeight});
$('body.slider-down-layer .slide-down-filter .filter-options-item').css({'width':noOfColumns, 'height':filterHeight});
}
if($('.slide-in-filter').length) {
$('.wp-ln-overlay').click(pageReset);
$('.wp-filters').click(pageSettings);
function pageSettings() {
$('.block-search, a.logo').css({'z-index': '5'});
$('body').addClass('wp-ln-open').css({'height': '100%', 'overflow': 'hidden'});
$('nav.navigation').css({'z-index': '1'});
$('div.columns').css({'z-index': '6'});
$('.wp-ln-overlay').fadeIn(100, 'linear', function () {
$('.slide-in-filter').delay(350).show("slide", {direction: "left"});
});
}
function pageReset() {
$('.slide-in-filter').hide('slide', {direction: "left"}, 500, function () {
$('body').removeClass('wp-ln-open').css({'height': 'auto', 'overflow': 'auto'});
$('.wp-ln-overlay').hide();
$('div.page-header').css({'z-index': ''});
$('div.columns').css({'z-index': '1'});
/** $('nav.navigation').css({'z-index': '3'}); */
$('.block-search, a.logo').css({'z-index': '5'});
$('.page-wrapper .nav-sections:not(.sticky-header-nav)').removeAttr('style');
});
}
} else if($('.slide-down-filter').length) {
$('.wp-filters').on('click', lnSlideDown);
function lnSlideDown() {
$('.wp-filters').off('click');
$('body').attr('data-pwmt', productWrapperMarginTop);
$('.products.wrapper').animate({marginTop: productWrapperMarginTop},
{
duration:500,
complete: function() {
$('.wp-filters span.wp-slide-down-add').addClass('active');
}
});
$('.wp-slide-down-add:not(active)').off('click');
$('.slide-down-filter').slideDown(500, function() {
$('.wp-filters').on('click', lnSlideUp);
});
}
function lnSlideUp() {
$('.wp-filters').off('click');
$('.slide-down-filter').slideUp(
{
duration: 500,
start: function(){
$('.products.wrapper').animate(
{
marginTop: '0px'
},
{
duration:500,
complete: function() {
$('.wp-filters span.wp-slide-down-add').removeClass('active');
$('.wp-filters').on('click', lnSlideDown);
},
queue: false
}
);
},
queue: false
});
}
} else {
$('body.slider-layer .toolbar-products').css({'margin-left': '0px'});
}
});
<?php if ($jsClass): ?>
require.config({
map: {
'*': {
"productListToolbarForm": "<?= /* @noEscape */ $jsClass; ?>"
}
}
});
<?php endif; ?>
require(['wpFilterSelect', 'wpInstantSearch', 'wpShowMoreLess'], function(){
wpFilterSelect.markSelected();
wpInstantSearch.searchOptions();
wpShowMoreLess.initMoreLess();
});
<?php if ($isStickyFiltersEnabled) : ?>
require([
"jquery",
"WeltPixel_LayeredNavigation/js/stickyFilters"
], function($, stickyFilters){
$(document).ready(function () {
'use strict';
let mobileThreshold = "768",
isStickyFiltersEnabled = "<?= /* @noEscape */ $isStickyFiltersEnabled ?>";
stickyFilters.init(mobileThreshold, isStickyFiltersEnabled);
});
});
<?php endif; ?>
</script>
</div>
<?php if ($horizontalSbDesignVersion === 'v3') : ?>
<style>
body.page-layout-1column #layered-filter-block.horizontal-v3 .block-content.filter-content .filter-options .filter-options-item .filter-options-title{
background-color: <?php /* @noEscape */ echo $filterButtonColor ?>;
color: <?php /* @noEscape */ echo $filterTextColor ?>;
border: <?php /* @noEscape */ echo $filtersBorder ?>;
border-radius: <?php /* @noEscape */ echo $filtersBorderRadius ?>;
border-radius: <?php /* @noEscape */ echo $filtersBorderRadius ?>;
border-radius: <?php /* @noEscape */ echo $filtersBorderRadius ?>;
border-color: <?php /* @noEscape */ echo $filtersBorderColor ?>;;
}
body.page-layout-1column #layered-filter-block.horizontal-v3 .block-content.filter-content .filter-options .filter-options-item .filter-options-title:after {
color: <?php /* @noEscape */ echo $filterTextColor ?>;
}
body.page-layout-1column #layered-filter-block.horizontal-v3 .block-content.filter-content .filter-options .filter-options-item .filter-options-title:hover,
body.page-layout-1column #layered-filter-block.horizontal-v3 .block-content.filter-content .filter-options .filter-options-item.active .filter-options-title,
body.page-layout-1column #layered-filter-block.horizontal-v3 .block-content.filter-content .filter-options .filter-options-item.active .filter-options-title:after{
background-color: <?php /* @noEscape */ echo $filterButtonHoverColor ?> ; ;
color: <?php /* @noEscape */ echo $filterTextHoverColor ?> ;
}
body.page-layout-1column #layered-filter-block.horizontal-v3 .block-content.filter-content .filter-options .filter-options-item .filter-options-title:hover::after {
color: <?php /* @noEscape */ echo $filterTextHoverColor ?>;
}
</style>
<?php endif; ?>
@@ -0,0 +1,3 @@
<script>
window.isLayeredNavigationEnabled = '<?= /* @noEscape */ $this->isLnEnabled()?>';
</script>
@@ -0,0 +1,83 @@
<?php
// @codingStandardsIgnoreFile
/** @var $block \WeltPixel\LayeredNavigation\Block\LayeredNavigation\RenderLayered */
?>
<?php $swatchData = $block->getSwatchData(); ?>
<?php $isMulti = $block->getIsMultiSelect($swatchData['attribute_id']) ?>
<div id="swatch-wrapper" class="swatch-attribute swatch-layered <?= $block->escapeHtmlAttr($swatchData['attribute_code']) ?>"
attribute-code="<?= $block->escapeHtmlAttr($swatchData['attribute_code']) ?>"
attribute-id="<?= $block->escapeHtmlAttr($swatchData['attribute_id']) ?>">
<div class="swatch-attribute-options clearfix" data-is-multi="<?= /* @noEscape */ (int)$block->getIsMultiSelect($swatchData['attribute_id']) ?>">
<?php foreach ($swatchData['options'] as $option => $label): ?>
<a href="<?= $block->escapeUrl($label['link']) ?>"
aria-label="<?= $block->escapeHtmlAttr($label['label']) ?>"
class="swatch-option-link-layered"
data-is-multi="<?= /* @noEscape */ (int) $isMulti ?>"
data-opt-path="<?= $block->escapeHtmlAttr($swatchData['attribute_code'] . '=' . $option) ?>"
id="wp_ln_swatch_attr_<?= $block->escapeHtmlAttr($swatchData['attribute_id']) ?>_<?= $block->escapeHtmlAttr($option) ?>">
<?php if (isset($swatchData['swatches'][$option]['type'])) { ?>
<?php switch ($swatchData['swatches'][$option]['type']) {
case '3':
?>
<div class="swatch-option <?= $block->escapeHtmlAttr($label['custom_style']) ?>"
tabindex="-1"
data-option-type="3"
data-option-id="<?= /* @noEscape */ $option ?>"
data-option-label="<?= /* @noEscape */ $label['label'] ?>"
data-option-tooltip-thumb=""
data-option-tooltip-value=""
></div>
<?php break;
case '2':
?>
<?php $swatchThumbPath = $block->getSwatchPath('swatch_thumb',
$swatchData['swatches'][$option]['value']); ?>
<?php $swatchImagePath = $block->getSwatchPath('swatch_image',
$swatchData['swatches'][$option]['value']); ?>
<div class="swatch-option image <?= $block->escapeHtmlAttr($label['custom_style']) ?>"
tabindex="-1"
data-option-type="2"
data-option-id="<?= /* @noEscape */ $option ?>"
data-option-label="<?= /* @noEscape */ $label['label'] ?>"
data-option-tooltip-thumb="<?= /* @noEscape */ $swatchThumbPath ?>"
data-option-tooltip-value=""
style="background: url(<?= $block->escapeUrl($swatchImagePath) ?>) no-repeat center; background-size: initial;"></div>
<?php break;
case '1':
?>
<div class="swatch-option color <?= $block->escapeHtmlAttr($label['custom_style']) ?>"
tabindex="-1"
data-option-type="1"
data-option-id="<?= /* @noEscape */ $option ?>"
data-option-label="<?= /* @noEscape */ $label['label'] ?>"
data-option-tooltip-thumb=""
data-option-tooltip-value="<?= /* @noEscape */ $swatchData['swatches'][$option]['value'] ?>"
style="background: <?= /* @noEscape */ $swatchData['swatches'][$option]['value'] ?> no-repeat center; background-size: initial;"></div>
<?php break;
case '0':
default:
?>
<div class="swatch-option text <?= $block->escapeHtmlAttr($label['custom_style']) ?>"
tabindex="-1"
option-type="0"
data-option-id="<?= /* @noEscape */ $option ?>"
data-option-label="<?= /* @noEscape */ $label['label'] ?>"
data-option-tooltip-thumb=""
data-option-tooltip-value=""
><?= /* @noEscape */ $swatchData['swatches'][$option]['value'] ?></div>
<?php break;
} ?>
<?php } ?>
</a>
<?php endforeach; ?>
</div>
</div>
<script>
require(["jquery", "Magento_Swatches/js/swatch-renderer"], function ($) {
$('.swatch-layered.<?= $block->escapeJs($swatchData['attribute_code']) ?>')
.find('[data-option-type="1"], [data-option-type="2"], [data-option-type="0"], [data-option-type="3"]')
.SwatchRendererTooltip();
});
</script>
@@ -0,0 +1,4 @@
<div id="layer-product-list">
<?php echo $block->getChildHtml() ?>
</div>
@@ -0,0 +1,3 @@
<div id="layer-product-list">
<?php echo $block->getChildHtml() ?>
</div>
@@ -0,0 +1,132 @@
<?php
/** @var \WeltPixel\LayeredNavigation\Helper\Data $wpHelper */
$wpHelper = $this->helper('\WeltPixel\LayeredNavigation\Helper\Data');
?>
<?php if (($wpHelper->getSidebarStyle() == 0) && $wpHelper->isShowHideDesktopFilterEnabled()) : ?>
<div class="show-hide-filter-desktop">
<div class="desktop-show-filter">
<span class="show-filter-icon"></span>
<?= $block->escapeHtml(__('Show Filters')) ?>
</div>
<div class="desktop-hide-filter active">
<span class="show-filter-icon"></span>
<?= $block->escapeHtml(__('Hide Filters')) ?>
</div>
</div>
<script>
require([
'jquery','mage/cookies'
], function ($) {
var colMainWidth = null, sidebarHideDurationDefault = 500;
var desktopHideFilterElm = $('.desktop-hide-filter'),
desktopShowFilterElm = $('.desktop-show-filter'),
defaultShowHideState = '<?= /* @noEscape */ $wpHelper->getShowHideDesktopFilterState() ?>';
function desktopHideFilter(element, hideQuickly) {
if (!$(element).hasClass('active')) {
return false;
}
let sidebarHideDuration = sidebarHideDurationDefault;
if (hideQuickly) {
sidebarHideDuration = 0;
} else {
$.cookie('wp_ln_showhide', 'hide');
}
$(element).hide().removeClass('active');
$('.desktop-show-filter').css('display', 'inline-block');
if (!colMainWidth) {
var width = $('.column.main').outerWidth();
var parentWidth = $('.column.main').offsetParent().width();
colMainWidth = (100*width/parentWidth - 0.1) + "%";
}
$(function() {
$('.sidebar').animate(
{
'opacity': '0',
'margin-left': '-300px'
},
{
duration: sidebarHideDuration,
queue: false,
complete: function() {
$(this).hide();
}
}
);
$('.column.main').addClass('no-left-padding').animate(
{
'width': '100%'
},
{
duration: 500,
queue: false,
complete: function() {
if (window.CategoryPage) {
window.CategoryPage.buttonQuickView();
window.CategoryPage.itemHeight(true);
}
$('.desktop-show-filter').addClass('active');
}
}
);
$('.toolbar.toolbar-products').addClass('auto-width').animate( {'padding-left' : '0'}, {duration: 500});
});
}
function desktopShowFilter(element) {
if (!$(element).hasClass('active')) {
return false;
}
$(element).hide().removeClass('active');
$('.desktop-hide-filter').css('display', 'inline-block');
$.cookie('wp_ln_showhide', 'show');
$(function() {
$('.sidebar').show().css('opacity', '1').animate(
{
'margin-left': '0'
},
{
duration: 500,
queue: false,
complete: function() {
$('.desktop-hide-filter').addClass('active');
}
}
);
$('.column.main').removeClass('no-left-padding').animate(
{
'width': colMainWidth
},
{
duration: 500,
queue: false,
complete: function() {
if (window.CategoryPage) {
window.CategoryPage.buttonQuickView();
window.CategoryPage.itemHeight(true);
}
}
}
);
});
$('.toolbar.toolbar-products').removeClass('auto-width').animate( {'padding-left' : '12px'}, {duration: 500});
}
desktopHideFilterElm.bind('click', function () {
desktopHideFilter(this, false);
});
desktopShowFilterElm.bind('click', function () {
desktopShowFilter(this);
});
$('.sidebar').addClass('desktop-showhide-filter-on')
if ($.cookie('wp_ln_showhide') == 'hide') {
desktopHideFilter(desktopHideFilterElm, true);
} else if ($.cookie('wp_ln_showhide') != 'show' && defaultShowHideState == 'closed') {
desktopHideFilter(desktopHideFilterElm, true);
}
});
</script>
<?php endif; ?>
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 177 B

@@ -0,0 +1,185 @@
/*!
* jQuery UI Touch Punch 0.2.3
*
* Copyright 2011–2014, Dave Furfero
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Depends:
* jquery.ui.widget.js
* jquery.ui.mouse.js
*/
define(['jquery', 'jquery-ui-modules/mouse', 'jquery-ui-modules/widget'], // Require jquery
function($){
(function ($) {
// Detect touch support
$.support.touch = 'ontouchend' in document;
// Ignore browsers without touch support
if (!$.support.touch) {
return;
}
var mouseProto = $.ui.mouse.prototype,
_mouseInit = mouseProto._mouseInit,
_mouseDestroy = mouseProto._mouseDestroy,
touchHandled;
/**
* Simulate a mouse event based on a corresponding touch event
* @param {Object} event A touch event
* @param {String} simulatedType The corresponding mouse event
*/
function simulateMouseEvent (event, simulatedType) {
// Ignore multi-touch events
if (event.originalEvent.touches.length > 1) {
return;
}
if (event.cancelable) {
event.preventDefault();
}
var touch = event.originalEvent.changedTouches[0],
simulatedEvent = document.createEvent('MouseEvents');
// Initialize the simulated mouse event using the touch event's coordinates
simulatedEvent.initMouseEvent(
simulatedType, // type
true, // bubbles
true, // cancelable
window, // view
1, // detail
touch.screenX, // screenX
touch.screenY, // screenY
touch.clientX, // clientX
touch.clientY, // clientY
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey
0, // button
null // relatedTarget
);
// Dispatch the simulated event to the target element
event.target.dispatchEvent(simulatedEvent);
}
/**
* Handle the jQuery UI widget's touchstart events
* @param {Object} event The widget element's touchstart event
*/
mouseProto._touchStart = function (event) {
var self = this;
// Ignore the event if another widget is already being handled
if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])) {
return;
}
// Set the flag to prevent other widgets from inheriting the touch event
touchHandled = true;
// Track movement to determine if interaction was a click
self._touchMoved = false;
// Simulate the mouseover event
simulateMouseEvent(event, 'mouseover');
// Simulate the mousemove event
simulateMouseEvent(event, 'mousemove');
// Simulate the mousedown event
simulateMouseEvent(event, 'mousedown');
};
/**
* Handle the jQuery UI widget's touchmove events
* @param {Object} event The document's touchmove event
*/
mouseProto._touchMove = function (event) {
// Ignore event if not handled
if (!touchHandled) {
return;
}
// Interaction was not a click
this._touchMoved = true;
// Simulate the mousemove event
simulateMouseEvent(event, 'mousemove');
};
/**
* Handle the jQuery UI widget's touchend events
* @param {Object} event The document's touchend event
*/
mouseProto._touchEnd = function (event) {
// Ignore event if not handled
if (!touchHandled) {
return;
}
// Simulate the mouseup event
simulateMouseEvent(event, 'mouseup');
// Simulate the mouseout event
simulateMouseEvent(event, 'mouseout');
// If the touch interaction did not move, it should trigger a click
if (!this._touchMoved) {
// Simulate the click event
simulateMouseEvent(event, 'click');
}
// Unset the flag to allow other widgets to inherit the touch event
touchHandled = false;
};
/**
* A duck punch of the $.ui.mouse _mouseInit method to support touch events.
* This method extends the widget with bound touch event handlers that
* translate touch events to mouse events and pass them to the widget's
* original mouse event handling methods.
*/
mouseProto._mouseInit = function () {
var self = this;
// Delegate the touch handlers to the widget's element
self.element.bind({
touchstart: $.proxy(self, '_touchStart'),
touchmove: $.proxy(self, '_touchMove'),
touchend: $.proxy(self, '_touchEnd')
});
// Call the original $.ui.mouse init method
_mouseInit.call(self);
};
/**
* Remove the touch event handlers
*/
mouseProto._mouseDestroy = function () {
var self = this;
// Delegate the touch handlers to the widget's element
self.element.unbind({
touchstart: $.proxy(self, '_touchStart'),
touchmove: $.proxy(self, '_touchMove'),
touchend: $.proxy(self, '_touchEnd')
});
// Call the original $.ui.mouse destroy method
_mouseDestroy.call(self);
};
})(jQuery);
});
@@ -0,0 +1,703 @@
define([
"jquery",
"loader",
"jquery-ui-modules/widget",
"jquery-ui-modules/effect-slide",
"Magento_Catalog/js/product/list/toolbar",
], function ($) {
/**
* ProductListToolbarForm Widget - this widget is setting cookie and submitting form according to toolbar controls
*/
$.widget('mage.productListToolbarForm', $.mage.productListToolbarForm, {
options:
{
modeControl: '[data-role="mode-switcher"]',
directionControl: '[data-role="direction-switcher"]',
orderControl: '[data-role="sorter"]',
limitControl: '[data-role="limiter"]',
pagerControl: '[data-role="pager"], .pages-items a',
mode: 'product_list_mode',
direction: 'product_list_dir',
order: 'product_list_order',
limit: 'product_list_limit',
pager: 'p',
modeDefault: 'grid',
directionDefault: 'asc',
orderDefault: 'position',
limitDefault: '9',
pagerDefault: '1',
productsToolbarControl: '.toolbar.toolbar-products',
productsListBlock: '#layer-product-list',
layeredNavigationFilterBlock: '.block.filter',
filterItemControl: '.block.filter .item a, .block.filter .filter-clear,.block.filter .swatch-option-link-layered, .wp-price-slider-a',
url: ''
},
_create: function () {
this._super();
this._bind($(this.options.pagerControl), this.options.pager, this.options.pagerDefault);
$(this.options.filterItemControl)
.off('click.' + this.namespace + 'productListToolbarForm')
.on('click.' + this.namespace + 'productListToolbarForm', {}, $.proxy(this.applyFilterToProductsList, this))
;
var that = this;
window.onpopstate = function(event) {
var ignoredHashes = ['#search-mod'];
if (event && !ignoredHashes.includes(window.location.hash) && window.location.href.slice(-1) != '#') {
var backUrl = event.target.location.origin + event.target.location.pathname;
var paramData = event.target.location.search.replace(/^\?/, '')
that.makeAjaxCall(backUrl, paramData, false);
}
}
$('.item a.wp-filter-disabled').off('click');
if (window.wp_ajax_useCustomPlaceholder == '1') {
$('.page-wrapper').loader({
icon: window.loadingImage,
template: '<div class="loading-mask" data-role="loader">\n' +
' <div class="loader">\n' +
' <img alt="<%- data.texts.imgAlt %>" style="max-width: ' + window.wp_ajax_placeholderCustomWidth + '" src="<%- data.icon %>">\n' +
' <p><%- data.texts.loaderText %></p>\n' +
' </div>\n' +
'</div>'
});
}
},
/**
* @param {jQuery.Event} event
* @private
*/
_processPagination: function (event) {
event.preventDefault();
var paginationUrl = event.currentTarget.href;
var urlParams = this.getUrlParams(paginationUrl);
this.changeUrl(
event.data.paramName,
urlParams[event.data.paramName],
event.data.default
);
},
_bind: function (element, paramName, defaultValue) {
/**
* Prevent double binding of these events because this component is being applied twice in the UIX
*/
if (paramName == this.options.pager) {
element
.off('click.' + this.namespace + 'productListToolbarForm')
.on('click.' + this.namespace + 'productListToolbarForm', {
paramName: paramName,
default: defaultValue
}, $.proxy(this._processPagination, this));
} else if (element.is("select")) {
element
.off('change.' + this.namespace + 'productListToolbarForm')
.on('change.' + this.namespace + 'productListToolbarForm', {
paramName: paramName,
default: defaultValue
}, $.proxy(this._processSelect, this));
} else {
element
.off('click.' + this.namespace + 'productListToolbarForm')
.on('click.' + this.namespace + 'productListToolbarForm', {
paramName: paramName,
default: defaultValue
}, $.proxy(this._processLink, this));
}
},
applyFilterToProductsList: function (evt) {
var link = $(evt.currentTarget),
linkA = link.attr('href'),
urlParts = (typeof linkA !== 'undefined') ? linkA.split('?') : '',
currentUrl = window.location.href,
isMulti = (link.attr('data-is-multi')) ? link.data('is-multi') : 0,
parentElem = link.parent(),
clickOpt = (parentElem.attr('data-path-opt')) ? parentElem.data('opt-path') : link.data('opt-path'),
c = currentUrl.split('?');
window.isSorting = false;
var reqeustParams = (typeof urlParts[1] === 'undefined') ? '' : urlParts[1];
var mergedPath = reqeustParams;
if (reqeustParams.length > 0 && typeof c[1] !== 'undefined') {
mergedPath = this.compareMergeParams(c[1], reqeustParams, clickOpt, isMulti);
}
self.elem = link;
this.makeAjaxCall(urlParts[0], mergedPath, true);
evt.preventDefault();
},
compareMergeParams: function (currentParamsStr, newParamsStr, clickOpt, isMulti) {
var a = currentParamsStr.split('&');
var b = newParamsStr.split('&');
var c = (typeof clickOpt !== 'undefined') ? clickOpt.split('=') : '';
var res = '';
a.sort();
b.sort();
for (var i = 0; i < b.length; i++) {
var paramStr = b[i].split('=')[0],
paramVal = decodeURIComponent(b[i].split('=')[1]),
paramArr = paramVal.split(',');
for (var j = 0; j < a.length; j++) {
if (typeof a[j] === 'undefined') {
continue;
}
var existParamStr = a[j].split('=')[0],
existParamVal = decodeURIComponent(a[j].split('=')[1]),
existParamArr = existParamVal.split(','),
matchParams = '';
if(paramStr == 'p' || paramStr == 'q' || paramStr == 'ajax') {
continue;
}
if (paramStr !== existParamStr) {
//res += paramStr + '=' + paramVal + '&';
continue;
}
for (var z = 0; z < existParamArr.length; z++) {
if (paramArr.indexOf(existParamArr[z]) !== -1) {
matchParams = (matchParams.length === 0) ? existParamArr[z] : matchParams + ',' + existParamArr[z];
}
}
if (paramStr === existParamStr && paramVal !== existParamVal && matchParams.length === 0 && isMulti != 0) {
paramVal = existParamVal + ',' + paramVal;
}
else if( c[0] == paramStr && c[1] == matchParams ){
var filteredArray = existParamArr.filter(function(e) { return e !== matchParams })
paramVal = (filteredArray.length > 0) ? filteredArray.join(',') : '';
}
else {
//paramVal = matchParams;
}
}
if(paramVal) {
res += paramStr + '=' + paramVal + '&';
}
}
res = res.slice(0, -1);
return res;
},
updateUrl: function (url, paramData, pushState) {
if (!url) {
return;
}
if (paramData && paramData.length > 0) {
url += '?' + paramData;
}
url = this.removeQueryStringParameter('ajax', url);
url = this.removeQueryStringParameter('_', url);
if (pushState && (typeof history.pushState === 'function')) {
history.pushState({}, null, url);
}
},
getParams: function (urlParams, paramName, paramValue, defaultValue) {
var decode = window.decodeURIComponent,
paramData = {},
parameters, i;
for (i = 0; i < urlParams.length; i++) {
parameters = urlParams[i].split('=');
paramData[decode(parameters[0])] = parameters[1] !== undefined ?
decode(parameters[1].replace(/\+/g, '%20')) :
'';
}
/** get the real attr name from param */
var paramValueArr = paramValue.split('~'),
paramValueNew = paramValueArr[0];
paramData[paramName] = paramValueNew;
/** get the given direction from param */
var directionName = this.options.direction;
if (paramValueArr.length == 2 && paramName != directionName) {
paramData[directionName] = paramValueArr[1];
}
return $.param(paramData);
},
_updateContent: function (content) {
window.shouldOpenMinicart = false;
$(this.options.productsToolbarControl).remove();
if (content.products_list) {
$(this.options.productsListBlock).html(content.products_list);
$(this.options.productsListBlock).trigger('contentUpdated');
}
if (content.filters) {
var isSlideIn = $('body').hasClass('slider-layer');
var isSlideDown = $('body').hasClass('slider-down-layer');
var isAutoClose = $('#layered-filter-block').hasClass('auto-close');
var isViewL = $('body').hasClass('wp-device-l');
var isViewXl = $('body').hasClass('wp-device-xl');
$(this.options.layeredNavigationFilterBlock).replaceWith(content.filters);
$(this.options.layeredNavigationFilterBlock).trigger('contentUpdated');
if(!isAutoClose && isSlideIn && !window.isSorting && (isViewL || isViewXl)) {
$('body').addClass('wp-ln-open').css({'height': '100%', 'overflow': 'hidden'});
$('.block-search, a.logo').css({'z-index': '1'});
$('.wp-ln-overlay').fadeIn(100, 'swing', function () {
$('#layered-filter-block').delay(150).show("slide", {direction: "left"});
});
}
if(!isAutoClose && isSlideDown && !window.isSorting) {
var productWrapperMarginTop = $('body').attr('data-pwmt');
$('.products.wrapper').animate({marginTop: productWrapperMarginTop},
{
duration:500,
complete: function() {
$('.wp-filters span.wp-slide-down-add').addClass('active');
}
});
$('.wp-slide-down-add:not(active)').off('click');
$('.slide-down-filter').slideDown(500);
$('body.slider-down-layer #layered-filter-block').show();
}
}
if (content.ga4ServerSideItemListHash) {
window.wpGA4ServerSide.pushViewItemList(content.ga4ServerSideItemListHash);
}
if (content.dataLayer) {
var dlObjects = JSON.parse(content.dataLayer);
window.dataLayer = window.dataLayer || [];
for (var i in dlObjects) {
window.dataLayer.push({ecommerce: null});
window.dataLayer.push(dlObjects[i]);
}
}
var allowGa4Services = true;
if (window.ga4AllowServices != undefined) {
allowGa4Services = window.ga4AllowServices;
}
if (content.dataLayerGA4 && allowGa4Services) {
var dl4Objects = JSON.parse(content.dataLayerGA4);
window.dataLayer = window.dataLayer || [];
for (var i in dl4Objects) {
window.dataLayer.push({ecommerce: null});
window.dataLayer.push(dl4Objects[i]);
}
}
$(document).trigger("wpproductlabels:init");
$('li.product-item').trigger('contentUpdated');
if (window.isSlCustomPopupUsed && parseInt(window.isSlCustomPopupUsed)) {
$('li.product-item').find('.towishlist').each(function() {
$(this).removeAttr('data-post');
})
}
$('body').trigger('contentUpdated');
},
lnSlideDown: function() {
var productWrapperMarginTop = $('body').attr('data-pwmt');
$('.products.wrapper').animate({marginTop: productWrapperMarginTop},
{
duration:500,
complete: function() {
$('.wp-filters span.wp-slide-down-add').addClass('active');
}
});
$('.wp-slide-down-add:not(active)').off('click');
$('.slide-down-filter').slideDown(500);
$('.wp-filters').on('click', this.lnSlideUp);
},
lnSlideUp: function() {
$('.wp-filters').off('click');
$('.slide-down-filter').slideUp(
{
duration: 500,
start: function(){
$('.products.wrapper').animate(
{
marginTop: '0px'
},
{
duration:500,
complete: function() {
$('.wp-filters span.wp-slide-down-add').removeClass('active');
$('.wp-filters').on('click', this.lnSlideDown);
},
queue: false
}
);
},
queue: false
});
},
reinitializeIas: function() {
if(require.defined('ias') && window.ajaxCatalog == 'infiniteScroll') {
jQuery.ias().destroy();
jQuery(function($) {
var config = {
container: '.products.wrapper .product-items',
item: '.product-item',
pagination: '.toolbar .pages, .toolbar .limiter',
next: '.pages .action.next',
negativeMargin: window.negativeMargin
};
var pagertext = jQuery(".toolbar-amount");
pagertext.show();
/** added to prevent jquery to add extra "_" parameter to link */
$.ajaxSetup({ cache: true });
/** add infinite-scroll class */
$(config.container).closest('.column.main').addClass('infinite-scroll');
/** load ias */
var ias = $.ias(config);
ias.getNextUrl = function(container) {
if (!container) {
container = ias.$container;
}
/** always take the last matching item + fix to be protocol relative */
var nexturl = $(ias.nextSelector, container).last().attr('href');
if(typeof nexturl !== "undefined") {
if (window.location.protocol == 'https:') {
nexturl = nexturl.replace('http:', window.location.protocol);
} else {
nexturl = nexturl.replace('https:', window.location.protocol);
}
nexturl = window.ajaxInfiniteScroll.removeQueryStringParameter('_', nexturl);
nexturl = window.ajaxInfiniteScroll.removeQueryStringParameter('ajax', nexturl);
}
return nexturl;
};
/** adds extra functionality to Infinite AJAX Scroll */
ias.extension(new IASPagingExtension());
ias.on('pageChange', function(pageNum, scrollOffset, url) {
window.page = pageNum;
});
/** added to prevent jquery to add extra "_" parameter to link */
ias.on('load', function(event) {
var url = event.url;
event.ajaxOptions.cache = true;
event.url = window.ajaxInfiniteScroll.removeQueryStringParameter('_', event.url);
});
ias.on('loaded', function(data, items) {
/** fix lazy load images */
window.ajaxInfiniteScroll.reloadImages(items);
window.ajaxInfiniteScroll.dataLayerUpdate(data);
});
/** fix ajax add to cart */
ias.on('rendered', function(items) {
window.ajaxInfiniteScroll.fixAddToCart();
/** re-init Pearl related elements */
window.ajaxInfiniteScroll.reloadQuickView();
window.ajaxInfiniteScroll.reloadCategoryPage();
/** update next/prev head links */
if (window.showCanonical == 1) {
window.ajaxInfiniteScroll.reloadCanonicalPrevNext();
}
$('.product-item-info a').each(function() {
if( typeof $(this).attr('data-item-page') === 'undefined') {
$(this).attr('data-item-page', window.page);
}
});
$(document).trigger("wpproductlabels:init");
$('li.product-item').trigger('contentUpdated');
if (window.isSlCustomPopupUsed && parseInt(window.isSlCustomPopupUsed)) {
$('li.product-item').find('.towishlist').each(function() {
$(this).removeAttr('data-post');
})
}
$.mage.formKey();
});
/** adds a text when there are no more pages to load */
ias.extension(new IASNoneLeftExtension({
html: '<span class="ias-no-more">' + window.textNoMore + '</span>'
}));
/** displays a customizable loader image when loading a new page */
var loadingHtml = '<div class="ias-spinner">';
loadingHtml += '<img src="{src}"';
if (window.wp_ajax_useCustomPlaceholder == '1') {
loadingHtml += "style='max-width:" + window.wp_ajax_placeholderCustomWidth +"'";
}
loadingHtml += '/>';
loadingHtml += '<span>' + window.textLoadingMore + '</span>';
loadingHtml += '</div>';
ias.extension(new IASSpinnerExtension({
src: window.loadingImage,
html: loadingHtml
}));
/** adds "Load More" and "Load Previous" button */
if (window.LoadMore > 0) {
ias.extension(new IASTriggerExtension({
text: window.textNext,
html: '<button class="button action ias-load-more" type="button"><span>{text}</span></button>',
textPrev: 'Load previous items',
htmlPrev: '<button class="button action ias-load-prev" type="button"><span>{text}</span></button>',
offset: window.LoadMore
}));
} else {
ias.extension(new IASTriggerExtension({
textPrev: 'Load previous items',
htmlPrev: '<button class="button action ias-load-prev" type="button"><span>{text}</span></button>',
offset: 1000
}));
}
/** adds history support */
ias.extension(new IASHistoryExtension({prev: '.previous'}));
});
}
},
updateContent: function (content) {
this._updateContent(content)
},
changeUrl: function (paramName, paramValue, defaultValue) {
var urlPaths = this.options.url.split('?'),
baseUrl = urlPaths[0],
urlParams = urlPaths[1] ? urlPaths[1].split('&') : [],
paramData = this.getParams(urlParams, paramName, paramValue, defaultValue);
window.isSorting = (paramName == 'product_list_order' || paramName == 'product_list_limit' || paramName == 'p') ? true : false;
if( paramName == 'product_list_mode') {// paramName == 'product_list_order' - to remove adavancedsorting by ajax
var ajaxParam = false;
for (var i = urlParams.length; i--;) {
if (urlParams[i] === 'ajax=1') {
urlParams.splice(i, 1);
ajaxParam = true;
}
}
if (ajaxParam) {
paramData = this.getParams(urlParams, paramName, paramValue, defaultValue);
}
location.href = baseUrl + (paramData.length ? '?' + paramData : '');
} else {
this.makeAjaxCall(baseUrl, paramData, true);
}
},
backToTop: function()
{
var stickyHeader = $('.sticky-header, .sticky-header-mobile'),
stickyHeaderHeight = 0;
if (stickyHeader.length) {
stickyHeaderHeight = parseInt(stickyHeader.outerHeight());
}
$('html, body').animate({
scrollTop: ($('.column.main').offset().top - stickyHeaderHeight)
}, 'slow');
},
makeAjaxCall: function (baseUrl, paramData, pushState) {
var self = this;
var isSlideIn = $('body').hasClass('slider-layer');
var ajaxScrollTop = $('#layered-filter-block').hasClass('ajax-scroll-top');
if (ajaxScrollTop && !isSlideIn) {
self.backToTop();
}
var showLoader = true;
if (window.wp_ajax_useCustomPlaceholder == '1' && window.isSorting) {
$('.page-wrapper').loader("show");
showLoader = false;
}
var jqxhr = $.ajax({
url: baseUrl,
data: (paramData && paramData.length > 0) ? paramData + '&ajax=1' : 'ajax=1',
type: 'get',
dataType: 'json',
global: false,
cache: true,
showLoader: showLoader,
beforeSend: function (xhr){
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
if(typeof window.page === 'undefined') {
window.page = $('.product-item-info a').last().attr('data-item-page');
}
}
}).done(function (response) {
if (response.success) {
$('.swatch-option-tooltip').hide();
self.updateUrl(baseUrl, paramData, pushState);
self.updateContent(response.html);
self.slidersUpdate();
}
});
jqxhr.always(function() {
if (window.wp_ajax_useCustomPlaceholder == '1') {
$('.page-wrapper').loader("hide");
}
/** fix lazy load image width */
$("img.lazy").each(function() {
$(this).css({'max-width':'100%'});
});
self.reinitializeIas();
$('.product.photo.product-item-photo').on('click', function(e) {
e.preventDefault();
var page = $(this).attr('data-item-page');
var url = window.location.href;
self.resetIasPagination(page, url);
var href = $(this).attr('href');
window.location.href = href;
});
$('.product-item-info a').each(function() {
if( typeof $(this).attr('data-item-page') === 'undefined') {
$(this).attr('data-item-page', window.page);
}
});
if(require.defined('ias') && window.ajaxCatalog == 'nextPage') {
window.ajaxInfiniteScroll.addPageSelector('.pages li.item a.page');
}
if ($('body').hasClass('slider-layer')) self.resetPage();
if ($('body').hasClass('slider-down-layer')) self.slideUpReset();
self.reloadQuickView();
window.shouldOpenMinicart = '1';
$.mage.formKey();
});
},
resetIasPagination: function(page, url) {
if(require.defined('ias') && window.ajaxCatalog == 'infiniteScroll') {
jQuery.ias().destroy();
var newUrl = url.replace(/(&p=|\?p=).*?(&|$)/,'$1' + page + '$2');
window.history.replaceState("", "", newUrl);
}
},
reloadQuickView: function() {
var quickView = $('.weltpixel-quickview');
if (quickView.length) {
$('.weltpixel-quickview').bind('click', function() {
var prodUrl = $(this).attr('data-quickview-url');
if (prodUrl.length) {
window.quickview.displayContent(prodUrl);
}
});
if (window.wpQwListMode == 'list') {
quickView.each(function (key, item) {
if (!$(item).hasClass('wp-qw-adjusted')) {
var imageWrapper = $(item).closest('.product-item').find('.product-item-info').get(0);
var imagePhotoLink = $(item).closest('.product-item-info').find('.product-item-photo').get(0);
$(imageWrapper).prepend('<div class="product photo product-item-photo product-image-list"></div>');
var imageCustomDiv = $(item).closest('.product-item-info').find('.product-image-list').get(0);
$(imagePhotoLink).appendTo(imageCustomDiv)
var imagePhoto = $(item).closest('.product-item-info').find('.product-image-list').get(0);
$(item).show().appendTo(imagePhoto);
$(item).addClass('wp-qw-adjusted');
$(item).css('display', '');
}
});
}
}
},
slidersUpdate: function () {
$('.wp-slide-in').not(':first').remove();
$('.wp-slide-out').not(':first').remove();
$('.wp-filters').not(':first').remove();
$('.wp-ln-overlay').not(':first').remove();
$('.wp-ln-slider-js').not(':first').remove();
$('.wp-ln-selected-js').not(':first').remove();
},
resetPage: function () {
var slideInBlock = $('#layered-filter-block');
if(slideInBlock.hasClass('auto-close')) {
//$('.slide-in-filter').hide('slide', {direction: "left"}, 500, function () {
$('body').removeClass('wp-ln-open').css({'height': 'auto', 'overflow': 'auto'});
$('.wp-ln-overlay').hide();
$('.block-search, a.logo').css({'z-index': '10'});
//});
}
},
slideUpReset: function () {
var slideDownBlock = $('#layered-filter-block');
if(slideDownBlock.hasClass('auto-close')) {
//$('.wp-slide-down-add.active').off('click');
//$('.wp-slide-down-add:not(active)').on('click', self.lnSlideDown());
$('.wp-filters span.wp-slide-down-add').removeClass('active');
$('.products.wrapper').animate({marginTop: '0px'}, 1000);
$('.slide-down-filter').slideUp(1000);
$('.wp-filters').off('click');
} else {
$('.wp-filters span.wp-slide-down-add').removeClass('active');
$('.wp-filters').off('click');
}
},
markSelected: function () {
var elem = self.elem.parent();
if(elem.hasClass('wp-ln-selected')) {
elem.removeClass('wp-ln-selected');
} else {
elem.addClass('wp-ln-selected');
}
},
removeQueryStringParameter: function (key, url)
{
if (!url) url = window.location.href;
var hashParts = url.split('#'),
regex = new RegExp("([?&])" + key + "=.*?(&|#|$)", "i");
if (hashParts[0].match(regex)) {
url = hashParts[0].replace(regex, '$1');
url = url.replace(/([?&])$/, '');
if (typeof hashParts[1] !== 'undefined' && hashParts[1] !== null)
url += '#' + hashParts[1];
}
return url;
},
getUrlParams: function (url) {
var params = {
p: "1"
};
var parser = document.createElement('a');
parser.href = url;
var query = parser.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
params[pair[0]] = decodeURIComponent(pair[1]);
}
return params;
}
});
return $.mage.productListToolbarForm;
});
@@ -0,0 +1,90 @@
define([
'jquery',
'mage/mage'
], function ($) {
"use strict";
let stickyFilters = {
options: {
mobileThreshold: '786',
isStickyFiltersEnabled: '0',
},
initialPosition: $('.block.filter').offset() && $('.block.filter').offset().top || 0,
init: function (mobileThreshold, isStickyFiltersEnabled) {
this.options.mobileThreshold = mobileThreshold;
this.options.isStickyFiltersEnabled = isStickyFiltersEnabled;
let that = this;
$(window).scroll(function () {
let screenWidth = $(window).width();
if (isStickyFiltersEnabled === '1' && (screenWidth >= mobileThreshold)) {
that.makeStickyFilters();
}
});
},
makeStickyFilters: function () {
let that = this,
horizontalFilters = $('.block.filter'),
sc = $(window).scrollTop(),
stickyMenuHeights = that.calculateStickyHeaderHeight(),
pageHeader = $('.page-wrapper div.sticky-header'),
containerShowLimit = that.initialPosition - stickyMenuHeights.outerHeight;
if (sc > containerShowLimit) {
pageHeader.addClass('no-box-shadow', 100);
horizontalFilters.addClass("sticky-filters filters-box-shadow");
horizontalFilters.css('top', stickyMenuHeights.height);
} else {
horizontalFilters.removeClass("sticky-filters filters-box-shadow");
pageHeader.removeClass('no-box-shadow', 100);
horizontalFilters.css('top', '');
}
},
calculateStickyHeaderHeight: function () {
let that = this,
headerSection = $('.page-wrapper div.page-header'),
navMenuSection = $('.page-wrapper div.sticky-header-nav'),
pageHeader = $('.page-wrapper div.sticky-header'),
stickyHeaderHeights = {
outerHeight: 0,
height: 0
};
switch (that.getHeaderVersion(headerSection)) {
case "v4":
if (headerSection.is(':visible') && navMenuSection.is(':visible')) {
stickyHeaderHeights.outerHeight = headerSection.outerHeight() + navMenuSection.outerHeight();
stickyHeaderHeights.height = navMenuSection.height() + $(".panel.wrapper").height();
}
break;
default :
if (pageHeader.is(':visible')) {
stickyHeaderHeights.height = pageHeader.height();
stickyHeaderHeights.outerHeight = pageHeader.height();
}
break;
}
return stickyHeaderHeights;
},
getHeaderVersion: function (headerSection) {
if (headerSection.hasClass('page-header-v1')) {
return 'v1';
} else if (headerSection.hasClass('page-header-v2')) {
return 'v2';
} else if (headerSection.hasClass('page-header-v3')) {
return 'v3';
} else if (headerSection.hasClass('page-header-v4')) {
return 'v4';
} else
return 'clean';
}
}
return stickyFilters;
});
@@ -0,0 +1,25 @@
define([
"jquery"
], function ($) {
"use strict";
window.wpFilterSelect = {
markSelected: function() {
$.each($('#wp_ln_shopby_items li'), function() {
var id = $(this).data('attr-id');
if(id) {
var filterElem = $('#wp_ln_attr_' + id);
var filterSwatchElem = $('#wp_ln_swatch_attr_' + id);
if(filterElem.length) {
filterElem.addClass('wp-ln-selected');
}
if(filterSwatchElem.length) {
filterSwatchElem.addClass('wp-ln-selected');
}
}
});
}
}
});
@@ -0,0 +1,30 @@
define([
"jquery"
], function ($) {
"use strict";
window.wpInstantSearch = {
searchOptions: function() {
$('.wp-instant-search-inp').keyup(function() {
var id, input, filter, li, a, i;
id = $(this).data('attr-id');
if(id) {
input = $('#instant_search_'+id);
filter = input.val().toUpperCase();
li = $('#'+ id + '_items li');
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
if (a.innerText.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
})
}
}
});
@@ -0,0 +1,69 @@
define([
"jquery"
], function ($) {
"use strict";
window.wpShowMoreLess = {
initMoreLess: function() {
$(document).ready(function(){
$.each($('.wp-ln-actions'), function() {
var visibleItems = $(this).attr('data-visibleItems'),
visibleItemsStep = $(this).attr('data-visibleItemsStep'),
attrId = $(this).attr('data-attrId'),
elId = attrId + '_items',
ulSize = $('#' + elId + ' li').length,
loadMoreId = '#loadMore_' + attrId,
showLessId = '#showLess_' + attrId,
x = parseInt(visibleItems),
initialX = x,
xStep = parseInt(visibleItemsStep);
if(visibleItems > 0 && visibleItems.length > 0 && visibleItems < 99 && ulSize > visibleItems) {
$(loadMoreId).show();
$("#"+ elId + " li:lt(" + visibleItems + ")").show();
$(showLessId).hide();
} else {
$("#"+ elId + " li").show();
$(loadMoreId).hide();
$(showLessId).hide();
}
$(loadMoreId).click(function () {
if(xStep == 99) {
$('#' + elId + ' li:lt(' + ulSize + ')').show();
$(this).hide();
$(showLessId).show();
} else {
x = ( x + xStep <= ulSize) ? x + xStep : ulSize;
$('#' + elId + ' li:lt(' + x + ')').show();
if(ulSize == x){
$(this).hide();
$(showLessId).show();
}else{
$(showLessId).show();
}
}
});
$(showLessId).click(function () {
if(xStep == 99) {
$('#' + elId + ' li:gt(' + x + ')').hide();
$('#' + elId + ' li:eq(' + x + ')').hide();
$(this).hide();
$(loadMoreId).show();
} else {
x = ( x - xStep < 0 || x == ulSize) ? initialX : x - xStep;
$('#' + elId + ' li').not(':lt(' + x + ')').hide();
if(x <= visibleItems){
$(this).hide();
$(loadMoreId).show();
}else{
$(loadMoreId).show();
}
}
});
});
});
}
}
});