$price = apply_filters( 'raw_woocommerce_price', $raw_price ); // some plugin uses a different hook, use it if the standard one did not change the price if ( $price === $raw_price && ( is_plugin_active( 'woocommerce-currency-switcher/index.php' ) || is_plugin_active( 'woocommerce-multicurrency/woocommerce-multicurrency.php' ) ) ) { $price = apply_filters( 'woocommerce_product_get_regular_price', $raw_price, null ); } if ($price === $raw_price && class_exists(\Yay_Currency\Helpers\YayCurrencyHelper::class)) { $apply_currency = \Yay_Currency\Helpers\YayCurrencyHelper::detect_current_currency(); $price = \Yay_Currency\Helpers\YayCurrencyHelper::calculate_price_by_currency( $raw_price, false, $apply_currency ); } if ( $price === $raw_price && function_exists( 'wcml_convert_price' ) ) { global $woocommerce_wpml; if (!empty($woocommerce_wpml) && !empty($woocommerce_wpml->multi_currency) && !is_null($woocommerce_wpml->multi_currency)) { $price = wcml_convert_price($raw_price); } } } return ( false === $dec ? $price : round( $price, $dec ) ); } public function preparePriceFilter( $minPrice = null, $maxPrice = null, $rate = null ) { if ( ! is_null( $minPrice ) ) { $minPrice = str_replace( ',', '.', $minPrice ); if ( ! is_numeric( $minPrice ) ) { $minPrice = null; } } if ( ! is_null( $maxPrice ) ) { $maxPrice = str_replace( ',', '.', $maxPrice ); if ( ! is_numeric( $maxPrice ) ) { $maxPrice = null; } } if ( is_null( $minPrice ) && is_null( $maxPrice ) ) { return false; } $metaQuery = array( 'key' => '_price', 'price_filter' => true, 'type' => 'DECIMAL(20,3)' ); list( $minPrice, $maxPrice ) = DispatcherWpf::applyFilters( 'priceTax', array( $minPrice, $maxPrice ), 'subtract' ); if ( is_null( $rate ) ) { $rate = $this->getCurrentRate(); } if ( is_null( $minPrice ) ) { $metaQuery['compare'] = '<='; $metaQuery['value'] = $maxPrice / $rate; } elseif ( is_null( $maxPrice ) ) { $metaQuery['compare'] = '>='; $metaQuery['value'] = $minPrice / $rate; } else { $metaQuery['compare'] = 'BETWEEN'; $metaQuery['value'] = array( $minPrice / $rate, $maxPrice / $rate ); } if (function_exists('wcpbc_the_zone') && wcpbc_the_zone()) { global $wpdb; $key = '_' . wcpbc_the_zone()->get_id() . '_price'; $value = $metaQuery['compare'] . ( is_array($metaQuery['value']) ? " '" . $metaQuery['value'][0] . "' AND '" . $metaQuery['value'][1] . "'" : "'" . $metaQuery['value'] . "'" ); $clauses = array( 'join' => array( ' LEFT JOIN ' . $wpdb->postmeta . ' as wpf_price ON (wpf_price.post_id=' . $wpdb->posts . ".ID AND wpf_price.meta_key='_price')", ' LEFT JOIN ' . $wpdb->postmeta . ' as wpf_price_wcpbc ON (wpf_price_wcpbc.post_id=' . $wpdb->posts . ".ID AND wpf_price_wcpbc.meta_key='" . $key . "')" ), 'where' => array( ' AND ((wpf_price_wcpbc.post_id is NOT NULL AND CAST(wpf_price_wcpbc.meta_value AS DECIMAL(20,3)) ' . $value . ') OR (wpf_price_wcpbc.post_id is NULL AND CAST(wpf_price.meta_value AS DECIMAL(20,3)) ' . $value . '))' ) ); $this->addFilterClauses( $clauses, false ); return array(); } if (class_exists( 'WC_Measurement_Price_Calculator' )) { $metaKeyId = $this->getMetaKeyId( '_price' ); if ( $metaKeyId ) { global $wpdb; $metaDataTable = DbWpf::getTableName( 'meta_data' ); $value = $metaQuery['compare'] . ( is_array($metaQuery['value']) ? " '" . $metaQuery['value'][0] . "' AND '" . $metaQuery['value'][1] . "'" : "'" . $metaQuery['value'] . "'" ); $clauses = array( 'join' => array(' INNER JOIN ' . $metaDataTable . ' as wpf_price_table ON (wpf_price_table.key_id=' . $metaKeyId . ' AND wpf_price_table.product_id=' . $wpdb->posts . '.ID)'), 'where' => array(' AND wpf_price_table.val_dec ' . $value), ); $this->addFilterClauses( $clauses, false ); return array(); } } add_filter( 'posts_where', array( $this, 'controlDecimalType' ), 9999, 2 ); return array( 'price_filter' => $metaQuery ); } public function controlDecimalType( $where ) { return preg_replace( '/DECIMAL\([\d]*,[\d]*\)\(20,3\)/', 'DECIMAL(20,3)', $where ); } public function getCurrentRate() { $price = 1000; $newPrice = $this->getCurrencyPrice( $price ); return $newPrice / $price; } public function addHiddenFilterQuery( $query ) { $hidden_term = get_term_by( 'name', 'exclude-from-catalog', 'product_visibility' ); if ( $hidden_term ) { $query[] = array( 'taxonomy' => 'product_visibility', 'field' => 'term_taxonomy_id', 'terms' => array( $hidden_term->term_taxonomy_id ), 'operator' => 'NOT IN' ); } return $query; } public function getTabContent() { return $this->getView()->getTabContent(); } public function getEditTabContent() { $id = ReqWpf::getVar( 'id', 'get' ); return $this->getView()->getEditTabContent( $id ); } public function getEditLink( $id, $tableTab = '' ) { $link = FrameWpf::_()->getModule( 'options' )->getTabUrl( $this->getCode() . '_edit' ); $link .= '&id=' . $id; if ( ! empty( $tableTab ) ) { $link .= '#' . $tableTab; } return $link; } public function render( $params ) { $p = array( 'id' => ( isset($params['id']) ? (int) $params['id'] : 0 ), 'mode' => ( isset($params['mode']) && 'widget' == $params['mode'] ? 'widget' : '' ), ); return $this->getView()->renderHtml( $p ); } public function renderProductsList( $params ) { $params = array(); return $this->getView()->renderProductsListHtml( $params ); } public function renderSelectedFilters( $params ) { $p = array( 'id' => ( isset($params['id']) ? (int) $params['id'] : 0 ), ); return FrameWpf::_()->isPro() ? $this->getView()->renderSelectedFiltersHtml( $p ) : ''; } public function showAdminErrors() { // check WooCommerce is installed and activated if ( ! $this->isWooCommercePluginActivated() ) { // WooCommerce install url $wooCommerceInstallUrl = add_query_arg( array( 's' => 'WooCommerce', 'tab' => 'search', 'type' => 'term', ), admin_url( 'plugin-install.php' ) ); $tableView = $this->getView(); $tableView->assign( 'errorMsg', $this->translate( 'For work with "' ) . WPF_WP_PLUGIN_NAME . $this->translate( '" plugin, You need to install and activate WooCommerce plugin.' ) ); // check current module if ( ReqWpf::getVar( 'page' ) == WPF_SHORTCODE || FrameWpf::_()->isWCLicense()) { // show message HtmlWpf::echoEscapedHtml( $tableView->getContent( 'showAdminNotice' ) ); } } } public function isWooCommercePluginActivated() { return class_exists( 'WooCommerce' ); } public function WC_pif_product_has_gallery( $classes ) { global $product; $post_type = get_post_type( get_the_ID() ); if ( wp_doing_ajax() ) { if ( 'product' == $post_type ) { if ( is_callable( 'WC_Product::get_gallery_image_ids' ) ) { $attachment_ids = $product->get_gallery_image_ids(); } else { $attachment_ids = $product->get_gallery_attachment_ids(); } if ( $attachment_ids ) { $classes[] = 'pif-has-gallery'; } } } return $classes; } public function YITH_hide_add_to_cart_loop( $link, $product ) { if ( wp_doing_ajax() ) { if ( get_option( 'ywraq_hide_add_to_cart' ) == 'yes' && class_exists( 'YITH_YWRAQ_Frontend' ) ) { return call_user_func_array( array( 'YITH_YWRAQ_Frontend', 'hide_add_to_cart_loop' ), array( $link, $product ) ); } } return $link; } /** * Add plugin compatibility wp_query filtering results args * * @link https://iconicwp.com/products/woocommerce-show-single-variations * * @param array $args query args * * @return array */ public function Iconic_Wssv_Query_Args( $args ) { $args = Iconic_WSSV_Query::add_variations_to_shortcode_query( $args, array() ); return $args; } public function addChildrenAttributeTerms( $parents ) { $aFlat = array(); foreach ( $parents as $id => $term ) { if ( !empty( $term->children ) ) { $aFlatChildren = $this->addChildrenAttributeTerms ( $term->children ); $term->children = array(); $aFlat[$id] = $term; foreach ( $aFlatChildren as $cid => $cterm ) { $aFlat[$cid] = $cterm; } } else { $aFlat[$id] = $term; } } return $aFlat; } public function getAttributeTerms( $slug ) { $terms = array(); if ( empty( $slug ) ) { return $terms; } $args = array( 'hide_empty' => false ); if ( is_numeric( $slug ) ) { $args['taxonomy'] = wc_attribute_taxonomy_name_by_id( (int) $slug ); $values = get_terms( $args ); } else { $values = DispatcherWpf::applyFilters( 'getCustomTerms', array(), $slug, $args ); $values = $this->addChildrenAttributeTerms( $values ); } if ( $values ) { foreach ( $values as $value ) { if ( ! empty( $value->term_id ) ) { $terms[ $value->term_id ] = $value->name; } } } return $terms; } public function getFilterTaxonomies( $settings, $calcCategories = false, $filterSettings = array(), $ajax = false, $urlQuery = array() ) { if ( empty( $urlQuery ) ) { $urlQuery = ReqWpf::get( 'get' ); } $multiLogic = $this->getFilterSetting( $filterSettings, 'f_multi_logic', 'and' ); $taxonomies = array(); $forCount = array(); $forCountWithChildren = array(); $other = array(); if ( $calcCategories ) { $taxonomies[] = 'product_cat'; } $key = 0; $differentLogic = array(); $difBlocks = array(); foreach ( $settings as $filter ) { if ( empty( $filter['settings']['f_enable'] ) ) { continue; } $taxonomy = ''; switch ( $filter['id'] ) { case 'wpfCategory': $taxonomy = 'product_cat'; break; case 'wpfTags': $taxonomy = 'product_tag'; break; case 'wpfAttribute': if ( ! empty( $filter['settings']['f_list'] ) ) { $slug = $filter['settings']['f_list']; $taxonomy = ( is_numeric( $slug ) ) ? wc_attribute_taxonomy_name_by_id( (int) $slug ) : DispatcherWpf::applyFilters( 'getCustomAttributeName', $slug, $filter ); } $frontendType = $this->getFilterSetting( $filter['settings'], 'f_frontend_type', '' ); if ( 'slider' === $frontendType ) { $showAllSliderAttributes = $this->getFilterSetting( $filter['settings'], 'f_show_all_slider_attributes', false ); if ( $showAllSliderAttributes ) { $other[] = $filter['id']; } } break; case 'wpfBrand': $taxonomy = 'product_brand'; break; case 'wpfPerfectBrand': $taxonomy = 'pwb-brand'; break; case 'wpfPrice': case 'wpfPriceRange': if ( ! $ajax || ( isset( $filterSettings['filter_recount_price'] ) && $filterSettings['filter_recount_price'] ) ) { $other[] = $filter['id']; } break; case 'wpfAuthor': case 'wpfVendors': case 'wpfRating': $other[] = $filter['id']; break; default: break; } if ( ! empty( $taxonomy ) ) { $typ = $this->getFilterSetting( $filter['settings'], 'f_frontend_type'); if (!in_array($typ, array('dropdown'))) { $settingName = ( 'product_cat' === $taxonomy ) ? 'f_multi_logic' : 'f_query_logic'; $queryLogic = $this->getFilterSetting( $filter['settings'], $settingName, 'and' ); if ( ( 'and' === $multiLogic && 'or' === $queryLogic ) || ( 'or' === $multiLogic && 'and' === $queryLogic ) ) { $differentLogic[ $key ] = $taxonomy; if (!isset($difBlocks[$taxonomy])) { $difBlocks[$taxonomy] = array(); } $difBlocks[$taxonomy][] = $key; } } $taxonomies[ $key ] = $taxonomy; if ( ! empty( $filter['settings']['f_show_count'] ) ) { $forCount[] = $taxonomy; if ( ! empty( $filter['settings']['f_show_count_parent_with_children'] ) ) { $forCountWithChildren[] = $taxonomy; } } } $key ++; } $getNames = array(); $checkGetNames = $this->getFilterSetting( $filterSettings, 'check_get_names', '0' ); if (!$checkGetNames) { // delete from get_names if more then one block with same taxonomy foreach ($difBlocks as $t => $keys) { if (count($keys) > 1) { foreach ($keys as $i => $k) { unset($differentLogic[$k]); } } } } if ( $checkGetNames || ! empty( $differentLogic ) ) { $getNames = $this->checkGetNames( $taxonomies, $other, $differentLogic, $urlQuery ); } return array( 'names' => array_unique( $taxonomies ), 'count' => array_unique( $forCount ), 'count_with_children' => array_unique( $forCountWithChildren ), 'other_names' => $other, 'get_names' => $getNames, 'multi_logic' => $multiLogic, 'check_get_names' => $checkGetNames, 'keep_recount_price' => $this->getFilterSetting($filterSettings, 'filter_recount_price', '0') && $this->getFilterSetting($filterSettings, 'keep_recount_price', '0'), 'cat_only_children' => DispatcherWpf::applyFilters( 'getOneByOneCategoryHierarchy', array(), $urlQuery, $filterSettings ), ); } /** * Forms an array with names from the address bar * * @param $taxonomies * * @return array */ public function checkGetNames( &$taxonomies, &$other, $differentLogic = array(), $urlQuery = array() ) { $blocks = array(); $getNames = array(); foreach ( $taxonomies as $index => $taxonomy ) { if ( empty( $differentLogic ) || ( isset( $differentLogic[ $index ] ) && $differentLogic[ $index ] === $taxonomy ) ) { switch ( $taxonomy ) { case 'product_cat': $blocks[ $taxonomy ][] = 'wpf_filter_cat.*?_' . $index; break; case 'product_tag': $blocks[ $taxonomy ][] = 'product_tag_' . $index; break; case 'pwb-brand': $blocks[ $taxonomy ][] = 'wpf_filter_pwb.*?_' . $index; break; default: if ( 0 === strpos( $taxonomy, 'flocal-' ) || 0 === strpos( $taxonomy, 'fmeta-' ) || 0 === strpos( $taxonomy, 'acf-' ) ) { $blocks[ $taxonomy ][] = $taxonomy; $blocks[ $taxonomy ][] = $taxonomy . '_' . $index; } else { $pattern = 'wpf_filter_' . preg_replace( '/^pa_/', '', $taxonomy ); $blocks[ $taxonomy ][] = $pattern; $blocks[ $taxonomy ][] = $pattern . '_' . $index; } break; } } } foreach ( $other as $index => $taxonomy ) { switch ( $taxonomy ) { case 'wpfRating': $blocks[ $taxonomy ][] = 'pr_rating'; break; } } if ( ! empty( $blocks ) ) { foreach ( $urlQuery as $param => $value ) { foreach ( $blocks as $taxanomy => $patterns ) { foreach ( $patterns as $pattern ) { preg_match( '/^' . $pattern . '$/', $param, $matches ); if ( isset( $matches[0] ) ) { $getNames[ $taxanomy ] = $param; continue 3; } } } } } return $getNames; } public function createTemporaryTable( $table, $sql, $postfix = '' ) { if ( '' !== $postfix ) { $table .= '_' . str_replace( '-', '_', trim( $postfix ) ); } $resultTable = $table; if ( isset( $this->clausesByParam['not_for_temporary_table'] ) ) { foreach ( $this->clausesByParam['not_for_temporary_table'] as $sqlPart ) { $sql = str_replace( $sqlPart, '', $sql ); } } $sql = str_replace( 'SQL_CALC_FOUND_ROWS', '', $sql ); $orderPos = strpos( $sql, 'ORDER' ); if ( $orderPos ) { $sql = substr( $sql, 0, $orderPos ); } else { $limitPos = strpos( $sql, 'LIMIT' ); if ( $limitPos ) { $sql = substr( $sql, 0, $limitPos ); } } $needPrimaryKey = DbWpf::get("SHOW SESSION variables like 'sql_require_primary_key'"); if (!empty($needPrimaryKey) && isset($needPrimaryKey[0]['Value']) && 'ON' == $needPrimaryKey[0]['Value']) { DbWpf::query('SET SESSION sql_require_primary_key=0'); } if ( ! DbWpf::query( "DROP TEMPORARY TABLE IF EXISTS `{$table}`") ) { return false; } if ( DbWpf::query( "CREATE TEMPORARY TABLE IF NOT EXISTS `{$table}` (index my_pkey (id)) AS {$sql}", true ) === false ) { $resultTable = '(' . $sql . ')'; } $this->tempTables[ $table ] = $resultTable; return $resultTable; } public function removeFromArgsForLogicOr( $removeArgs, $args ) { $calc = array(); foreach ( $removeArgs as $taxonomy => $param ) { $argsTemp = $args; foreach ( $argsTemp['tax_query'] as $index_1 => $tax_1 ) { if ( is_array( $tax_1 ) ) { if ( isset( $tax_1['taxonomy'] ) ) { if ( $tax_1['taxonomy'] === $taxonomy ) { unset( $argsTemp['tax_query'][ $index_1 ] ); } } elseif ( is_array( $argsTemp['tax_query'][ $index_1 ] ) ) { foreach ( $argsTemp['tax_query'][ $index_1 ] as $index_2 => $tax_2 ) { if ( isset( $tax_2['taxonomy'] ) && $tax_2['taxonomy'] === $taxonomy ) { unset( $argsTemp['tax_query'][ $index_1 ][ $index_2 ] ); } } } } } $calc[ $param ] = $argsTemp; $calc[ $param ]['wpf_get_names_taxonomy'] = $taxonomy; } return $calc; } public function addToArgsForLogicAnd( $addArgs, $args, $urlQuery = array() ) { $calc = array(); if ( empty( $urlQuery ) ) { $urlQuery = ReqWpf::get( 'get' ); } foreach ( $addArgs as $taxonomy => $param ) { if ( isset( $urlQuery[ $param ] ) ) { $calc[ $param ] = $this->getQueryVars( $args, array(), array( $param => $urlQuery[ $param ] ) ); $calc[ $param ]['wpf_get_names_taxonomy'] = $taxonomy; } } return $calc; } /** * Get filter existing individual filters items * * @param int | null $args wp_query args * @param array $taxonomies * @param int | null $calcCategory * @param int | bool $prodCatId * @param array $generalSettings * @param bool $ajax * @param array $currentSettings * * @return mixed */ public function getFilterExistsItems( $args, $taxonomies, $calcCategory = null, $prodCatId = false, $generalSettings = array(), $ajax = false, $currentSettings = array(), $settings = array(), $urlQuery = array() ) { if ( empty( $taxonomies['names'] ) && empty( $taxonomies['other_names'] ) && empty( $taxonomies['get_names'] ) ) { return false; } $calc = array(); $isGetNames = ! empty( $taxonomies['get_names'] ); $multiLogicOr = ( 'or' === $taxonomies['multi_logic'] ); if ( ! empty( $taxonomies['names'] ) || ! empty( $taxonomies['other_names'] ) ) { list( $args, $argsFiltered ) = $this->getArgsWCQuery( $args, $currentSettings ); $calc = ( empty( $argsFiltered ) ) ? array( 'full' => $args ) : array( 'full' => $argsFiltered, 'light' => $args ); } if ( $multiLogicOr ) { if ( isset( $calc['light'] ) ) { $calc['full'] = $calc['light']; unset( $calc['light'] ); } elseif ( $ajax ) { $lightFromSession = ReqWpf::getVar( 'wpf_light', 'session' ); if ( isset( $lightFromSession ) ) { $calc['full'] = $lightFromSession; } } if ( $isGetNames ) { $calc = array_merge( $calc, $this->addToArgsForLogicAnd( $taxonomies['get_names'], $calc['full'], $urlQuery ) ); } } else { if ( $isGetNames ) { $calc = array_merge( $calc, $this->removeFromArgsForLogicOr( $taxonomies['get_names'], $calc['full'] ) ); } } $result = array( 'exists' => array() ); $tempTable = $this->tempFilterTable; foreach ( $calc as $mode => $args ) { if ( isset( $args['wpf_get_names_taxonomy'] ) ) { $taxonomy = (array) $args['wpf_get_names_taxonomy']; } elseif ( isset( $args['args'] ) ) { $taxonomy = [ $args['taxonomy'] ]; $args = $args['args']; } else { $taxonomy = $taxonomies['names']; } $param = array( 'ajax' => $ajax, 'prodCatId' => $prodCatId, 'generalSettings' => $generalSettings, 'currentSettings' => $currentSettings, ); $args = $this->addArgs( $args, $param ); $isCalcCategory = ! is_null( $calcCategory ); $param = array( 'isCalcCategory' => $isCalcCategory, 'calcCategory' => $calcCategory, 'taxonomy' => $taxonomy, 'generalSettings' => $generalSettings, 'mode' => $mode, 'forCount' => $taxonomies['count'], 'forCountWithChildren' => $taxonomies['count_with_children'], 'withCount' => ( ! empty( $taxonomies['count'] ) || $isCalcCategory ), 'isInStockOnly' => ( get_option( 'woocommerce_hide_out_of_stock_items', 'no' ) === 'yes' ), 'currentSettings' => $currentSettings, 'ajax' => $ajax, 'onlyCategories' => $taxonomies['cat_only_children'], ); // the search-everything plugin contains an error while adding the arguments if ( is_plugin_active( 'search-everything/search-everything.php' ) ) { remove_all_filters( 'posts_search' ); } remove_filter( 'posts_request', 'relevanssi_prevent_default_request' ); remove_filter( 'the_posts', 'relevanssi_query', 99 ); $existTerms = array(); $calcCategories = array(); $this->isLightMode = ( 'light' === $mode ) || ( ! empty( $this->clausesLight ) && ! key_exists( 'light', $calc ) ); $args['orderby'] = 'ID'; $args['order'] = 'ASC'; if ( ! empty( $args['meta_key'] ) && empty( $args['meta_value'] ) && empty( $args['meta_value_num'] ) ) { $args['meta_key'] = ''; } $isModeStandart = in_array( $mode, array( 'full', 'light' ), true ); $args = DispatcherWpf::applyFilters( 'addExistFilterArgs', $args ); if ( ! empty( $this->clauses ) && ( ( ! $multiLogicOr && ! $isModeStandart ) || ( $multiLogicOr && $isModeStandart ) ) ) { $filterLoop = $this->getFilterLoopFromMode( $mode, $args ); } else { $filterLoop = new WP_Query( $args ); } $this->isLightMode = false; $listTable = ''; $havePosts = $filterLoop->have_posts(); $onlyHaveFound = !empty($currentSettings['only_have_found']); if ( $havePosts && !$onlyHaveFound ) { $createOtherTemporaryTable = false; if ( isset( $this->clausesByParam['variation']['base_request'] ) ) { $query = ''; if ( ! $isModeStandart && ! $multiLogicOr && isset( $args['wpf_get_names_taxonomy'] )) { $query = $this->clausesByParam['variation']['base_request'][1]; foreach ( $this->clausesByParam['variation']['conditions'] as $currentTax => $conditions ) { if ( $currentTax !== $args['wpf_get_names_taxonomy'] ) { if ( isset( $conditions['join'] ) ) { $query .= implode( '', $conditions['join'] ); } } } $query .= $this->clausesByParam['variation']['base_request'][2]; $where = ''; foreach ( $this->clausesByParam['variation']['conditions'] as $currentTax => $conditions ) { if ( $currentTax !== $args['wpf_get_names_taxonomy'] ) { if ( isset( $conditions['where'] ) ) { $where .= ' AND ' . implode( ' AND ', $conditions['where'] ); } } } if ( '' !== $where ) { $query .= $where; } $query .= $this->clausesByParam['variation']['base_request'][3]; $first = true; foreach ( $this->clausesByParam['variation']['conditions'] as $currentTax => $conditions ) { if ( $currentTax !== $args['wpf_get_names_taxonomy'] ) { if ( isset( $conditions['having'] ) ) { if ( $first ) { $query .= ' HAVING '; $first = false; } $query .= implode( '', $conditions['having'] ); } } } } if ( $isModeStandart && $multiLogicOr ) { $query = implode( '', $this->clausesByParam['variation']['base_request'] ); } if ( '' !== $query ) { $baseTable = $this->createTemporaryTable( $this->tempVarTable, $query, $mode ); $filterLoop->request = str_replace( $this->tempVarTable, $baseTable, $filterLoop->request ); $listTable = $this->createTemporaryTable( $tempTable, $filterLoop->request, $mode ); $createOtherTemporaryTable = true; } } if ( ! $createOtherTemporaryTable ) { $postfix = ( $isModeStandart ) ? '' : $mode; $listTable = $this->createTemporaryTable( $tempTable, $filterLoop->request, $postfix ); } if ( ! empty( $listTable ) ) { if ( isset( $args['product_cat'] ) && $this->getFilterSetting( $currentSettings, 'display_only_children_category', false ) ) { $term = get_term_by( 'slug', $args['product_cat'], 'product_cat' ); if ( $term ) { $param['only_children_category'] = get_term_children( $term->term_id, 'product_cat' ); } } list( $existTerms, $calcCategories ) = $this->getTerms( $listTable, $param ); } } switch ( $mode ) { case 'full': $result['exists'] = $existTerms; $result['categories'] = $calcCategories; $result['have_posts'] = $havePosts ? 1 : 0; break; case 'light': $result['all'] = $existTerms; break; default: if ( ! empty( $existTerms ) ) { $result['exists'] = array_replace( $result['exists'], $existTerms ); } elseif ( is_array( $taxonomy ) ) { $currentTax = current( $taxonomy ); if ( isset( $result['exists'][ $currentTax ] ) ) { $result['exists'][ $currentTax ] = array_fill_keys( array_flip( $result['exists'][ $currentTax ] ), 0 ); } } break; } if (!$onlyHaveFound) { //if ( ( 'full' === $mode && ! key_exists( 'light', $calc ) ) || 'light' === $mode ) { if ( 'full' === $mode || 'light' === $mode ) { $param = array_merge( $param, array( 'listTable' => $listTable, 'havePosts' => $havePosts, 'taxonomies' => $taxonomies, 'calcMode' => $mode, 'calcVars' => $calc, ) ); $result = $this->getExistsMore( $args, $param, $result ); } } } $this->isLightMode = false; if ( '1' === ReqWpf::getVar( 'wpf_skip' ) ) { $recalculateFilters = $this->getFilterSetting( $settings, 'recalculate_filters', false ); if ( $recalculateFilters ) { $fid = ReqWpf::getVar( 'wpf_fid' ); $jsFound = ( ! is_null( $fid ) && ! empty( $fid ) ? 'wpfDoActionsAfterLoad(' . $fid . ',' . ( empty( $result['have_posts'] ) ? 0 : 1 ) . ');' : '' ); $result['existsTermsJS'] = '
'; } } return $result; } /** * Returns previously stored arguments in an object * * @param $args * * @return array */ public function getArgsWCQuery( $args, $currentSettings ) { $argsFiltered = ''; $postType = ''; $doNotUseShortcode = $this->getFilterSetting( $currentSettings, 'do_not_use_shortcut', false ); if ( $doNotUseShortcode ) { if ( empty( $this->mainWCQuery ) ) { $q = new WP_Query( DispatcherWpf::applyFilters( 'beforeFilterExistsTermsWithEmptyArgs', array( 'post_type' => 'product', 'meta_query' => array(), 'tax_query' => array() ) ) ); $this->loadProductsFilter( $q ); } $args = $this->mainWCQuery; $argsFiltered = $this->mainWCQueryFiltered; return array( $args, $argsFiltered ); } if ( is_null( $args ) ) { $filterId = $this->currentFilterId; $filterKey = $this->shortcodeFilterKey . $filterId; $existSC = ( count( $this->shortcodeWCQuery ) > 0 ); if ( ! $doNotUseShortcode && ! isset( $this->shortcodeWCQuery[ $filterKey ] ) ) { $filterKey = '-'; } if ( $existSC && isset( $this->shortcodeWCQuery[ $filterKey ] ) ) { $args = $this->shortcodeWCQuery[ $filterKey ]; $argsFiltered = isset( $this->shortcodeWCQueryFiltered[ $filterKey ] ) ? $this->shortcodeWCQueryFiltered[ $filterKey ] : ''; $postType = isset( $args['post_type'] ) ? $args['post_type'] : ''; } if ( 'product' != $postType && ( ! is_array( $postType ) || ! in_array( 'product', $postType ) ) ) { $args = $this->mainWCQuery; $argsFiltered = $this->mainWCQueryFiltered; $postType = isset( $args['post_type'] ) ? $args['post_type'] : ''; if ( 'product' !== $postType && ( ! is_array( $postType ) || ! in_array( 'product', $postType, true ) ) ) { if ( $existSC ) { $args = reset( $this->shortcodeWCQuery ); $argsFiltered = reset( $this->shortcodeWCQueryFiltered ); $postType = isset( $args['post_type'] ) ? $args['post_type'] : ''; } } } if ( 'product' !== $postType && ( ! is_array( $postType ) || ! in_array( 'product', $postType, true ) ) ) { $q = new WP_Query( DispatcherWpf::applyFilters( 'beforeFilterExistsTermsWithEmptyArgs', array( 'post_type' => 'product', 'meta_query' => array(), 'tax_query' => array() ) ) ); $this->loadProductsFilter( $q ); $args = $this->mainWCQuery; $argsFiltered = $this->mainWCQueryFiltered; } if ( $doNotUseShortcode && 'product' !== $postType && ( ! is_array( $postType ) || ! in_array( 'product', $postType, true ) ) ) { $filterKey = '-'; if ( $existSC && isset( $this->shortcodeWCQuery[ $filterKey ] ) ) { $args = $this->shortcodeWCQuery[ $filterKey ]; $argsFiltered = isset( $this->shortcodeWCQueryFiltered[ $filterKey ] ) ? $this->shortcodeWCQueryFiltered[ $filterKey ] : ''; } } } if (!$this->isFiltered(false) && $this->getFilterSetting( $currentSettings, 'all_products_filtering', false ) && $this->getFilterSetting( $currentSettings, 'form_filter_by_all_products', false )) { $exclude = array( 'paged', 'posts_per_page', 'post_type', 'wc_query', 'orderby', 'order', 'fields' ); foreach ( $args as $key => $value ) { if ( ! in_array( $key, $exclude ) ) { if ( is_string( $value ) ) { $args[$key] = ''; } if ( is_array( $value ) ) { $args[$key] = array(); } } } } return array( $args, $argsFiltered ); } /** * Adds arguments to $args array * * @param $args * @param $param * * @return array */ public function addArgs( $args, $param ) { if ( isset( $args['taxonomy'] ) ) { unset( $args['taxonomy'], $args['term'] ); } if ( is_null( $args ) || empty( $args ) || ! isset( $args['post_type'] ) || ( 'product' !== $args['post_type'] && ( is_array( $args['post_type'] ) && ! in_array( 'product', $args['post_type'], true ) ) ) ) { $args = array( 'post_status' => 'publish', 'post_type' => 'product', 'ignore_sticky_posts' => true, 'tax_query' => array(), ); } $addEFC = true; if ( isset( $args['tax_query'] ) ) { $i = $this->searchValueQuery( $args['tax_query'], 'taxonomy', 'product_visibility', false ); $taxQ = ( is_numeric( $i ) && isset( $args['tax_query'][ $i ] ) ? $args['tax_query'][ $i ] : false ); if ( ! $taxQ && is_array( $args['tax_query'] ) ) { foreach ( $args['tax_query'] as $k => $tax ) { if ( is_array( $tax ) ) { $i = $this->searchValueQuery( $tax, 'taxonomy', 'product_visibility', false ); if ( is_numeric( $i ) && isset( $tax[ $i ] ) ) { $taxQ = $tax[ $i ]; break; } } } } if ( $taxQ ) { if ( isset( $taxQ['operator'] ) && ( 'NOT IN' == $taxQ['operator'] ) && isset( $taxQ['field'] ) && isset( $taxQ['terms'] ) ) { $exludeTerm = get_term_by( 'name', 'exclude-from-catalog', 'product_visibility', ARRAY_A ); if ( $exludeTerm && isset( $exludeTerm[ $taxQ['field'] ] ) && is_array( $taxQ['terms'] ) && in_array( $exludeTerm[ $taxQ['field'] ], $taxQ['terms'] ) ) { $addEFC = false; } } } } if ( $addEFC ) { $args['tax_query'][] = array( 'taxonomy' => 'product_visibility', 'field' => 'name', 'terms' => 'exclude-from-catalog', 'operator' => 'NOT IN', ); } if ( $param['prodCatId'] ) { $args['tax_query'][] = array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $param['prodCatId'], ); } /*$args['nopaging'] = true; $args['posts_per_page'] = - 1;*/ $args['nopaging'] = false; $args['posts_per_page'] = 1; $args['hide_empty'] = 1; $args['fields'] = 'ids'; if ( class_exists( 'Iconic_WSSV_Query' ) ) { $args = $this->Iconic_Wssv_Query_Args( $args ); } //Integration with AJAX Search for WooCommerce /* * Plugin URL: https://wordpress.org/plugins/ajax-search-for-woocommerce/ * Author: Damian Góra */ if ( class_exists( 'DGWT_WC_Ajax_Search' ) ) { $searchIds = apply_filters( 'dgwt/wcas/search_page/result_post_ids', array() ); if ( $searchIds && is_array( $searchIds ) ) { $postIds = isset( $args['post__in'] ) ? $args['post__in'] : ''; if ( is_array( $postIds ) && ! empty( $postIds ) ) { if ( 1 !== count( $postIds ) || 0 !== $postIds[0] ) { $args['post__in'] = array_intersect( $postIds, $searchIds ); } } else { $args['post__in'] = $searchIds; } $args['s'] = ''; } } if ( ! empty( $args['post__in'] ) && ( 'product' === $args['post_type'] ) ) { $args['post_type'] = array( 'product', 'product_variation' ); } $args = $this->addWooOptions( $args ); foreach ( $param['generalSettings'] as $filter ) { $settings = ( isset( $filter['settings'] ) ) ? $filter['settings'] : []; $hiddens = array( 'f_hidden_brands', 'f_hidden_categories', 'f_hidden_attributes', 'f_hidden_tags' ); $replace = false; foreach ( $hiddens as $hidden ) { if ( $this->getFilterSetting( $settings, $hidden ) ) { $replace = true; } } if ( $replace ) { foreach ( $args['tax_query'] as &$tax ) { if ( isset ( $tax['wpf_group'] ) && $tax['wpf_group'] === $filter['name'] && isset( $tax[0]['terms'] ) ) { $tax[0]['terms'] = $settings['f_mlist[]']; } } } } return DispatcherWpf::applyFilters( 'addFilterExistsItemsArgs', $args ); } /** * Returns items in filter blocks * * @param $filterLoop * @param $param * * @return array */ public function getTerms( $listTable, $param ) { $calcCategories = array(); $childs = array(); $names = array(); $colorGroup = array(); $addSqls = array(); $curSettings = ( isset($param['currentSettings']) ? $param['currentSettings'] : array() ); $byVariations = ( !empty($curSettings['filtering_by_variations']) && !empty($curSettings['form_filter_by_variations']) ); $customPrefixes = DispatcherWpf::applyFilters( 'getCustomPrefixes', array(), false ); if ( empty( $customPrefixes ) ) { $taxonomyList = $param['taxonomy']; } else { $taxonomyList = array(); foreach ( $param['taxonomy'] as $i => $tax ) { $pos = strpos( $tax, '-' ); if ( ! $pos || ! in_array( substr( $tax, 0, $pos + 1 ), $customPrefixes, true ) ) { $taxonomyList[] = $tax; } } } global $wpdb; $sql = array(); $stockJoin = ''; if ($param['isInStockOnly']) { $metaKeyId = $this->getMetaKeyId('_stock_status'); if ($metaKeyId) { $valueId = FrameWpf::_()->getModule('meta')->getModel('meta_values')->getMetaValueId($metaKeyId, 'outofstock'); $stockJoin = ' INNER JOIN @__meta_data pm ON (pm.product_id=wpf_temp.ID AND pm.key_id=' . $metaKeyId . ' AND pm.val_id!=' . $valueId . ')'; } else { $stockJoin = ' INNER JOIN ' . $wpdb->postmeta . " pm ON (pm.post_id=wpf_temp.ID AND pm.meta_key='_stock_status' AND pm.meta_value!='outofstock')"; } } if ( ! empty( $taxonomyList ) ) { $addSqls['main']['withCount'] = $param['withCount']; $addSqls['main']['fields'] = ( $param['withCount'] ? '' : 'DISTINCT ' ) . 'tr.term_taxonomy_id, tt.term_id, tt.taxonomy, tt.parent' . ( $param['withCount'] ? ', COUNT(*) as cnt' : '' ); $addSqls['main']['taxonomyList'] = implode( "', '", $taxonomyList ); if ($byVariations) { $attrTaxonomyList = array(); $case = ''; $mainAttrId = $this->getMetaKeyId('_product_attributes'); if ($mainAttrId) { foreach ($taxonomyList as $tax) { if (strpos($tax, 'pa_') === 0) { $metaKeyId = $this->getMetaKeyId('attribute_' . $tax); if ($metaKeyId) { $isForVars = FrameWpf::_()->getModule( 'meta' )->getModel( 'meta_values' )->getMetaValueId($mainAttrId, '1', array('key2' => 'is_variation', 'key3' => $tax)); if ($isForVars) { $attrTaxonomyList[$tax] = $metaKeyId; $case .= ' WHEN md_attr.key_id=' . $metaKeyId . " THEN '" . $tax . "'"; } } } } } if (!empty($attrTaxonomyList)) { //$query = 'SELECT wpf_temp.id, p_vars.id as child, md_vals.value, (CASE ' . $case . " ELSE '' END) as taxonomy" . $query = "SELECT wpf_temp.id, p_vars.id as child, md_vals.value, REPLACE(md_keys.meta_key, 'attribute_', '') as taxonomy" . ' FROM ' . $listTable . ' as wpf_temp' . ' INNER JOIN #__posts as p_vars on (p_vars.post_parent=wpf_temp.id)' . ' INNER JOIN @__meta_data as md_attr ON (md_attr.product_id=p_vars.ID AND md_attr.key_id IN (' . implode(',', $attrTaxonomyList) . '))' . ' INNER JOIN @__meta_values as md_vals ON (md_vals.id=md_attr.val_id)' . ' INNER JOIN @__meta_keys as md_keys ON (md_keys.id=md_attr.key_id)' . str_replace('wpf_temp.', 'p_vars.', $stockJoin); $listVariationAttributes = $this->createTemporaryTable($this->tempFilterTable . '_var_attrs', $query); $typeJoin = ''; $metaKeyId = $this->getMetaKeyId('_wpf_product_type'); if ($metaKeyId) { $variableMetaId = FrameWpf::_()->getModule('meta')->getModel('meta_values')->getMetaValueId($metaKeyId, 'variable'); if ($variableMetaId) { $typeJoin = ' INNER JOIN @__meta_data md_type ON (md_type.product_id=wpf_temp.ID AND md_type.key_id=' . $metaKeyId . ')'; } } if (empty($typeJoin)) { $byVariations = false; } } else { $byVariations = false; } } } $taxonomyList = array(); $colorGroup = DispatcherWpf::applyFilters( 'getColorGroupForExistTerms', array(), $param ); if ( ! empty( $colorGroup ) ) { foreach ( $param['taxonomy'] as $key => $tax ) { if ( key_exists( $tax, $colorGroup ) ) { unset( $param['taxonomy'][ $key ] ); $taxonomyList[] = $tax; } } $addSqls['color']['withCount'] = false; $addSqls['color']['fields'] = 'tt.term_id, tt.taxonomy, wpf_temp.ID'; $addSqls['color']['taxonomyList'] = implode( "', '", $taxonomyList ); } foreach ( $addSqls as $key => $addSql ) { $sql[ $key ] = 'SELECT ' . $addSql['fields'] . ' FROM ' . $listTable . ' AS wpf_temp INNER JOIN ' . $wpdb->term_relationships . ' tr ON (tr.object_id=wpf_temp.ID) INNER JOIN ' . $wpdb->term_taxonomy . ' tt ON (tt.term_taxonomy_id=tr.term_taxonomy_id) '; /*if ( $addSql['withCount'] && $param['isInStockOnly'] ) { $metaKeyId = $this->getMetaKeyId( '_stock_status' ); if ( $metaKeyId ) { $valueId = FrameWpf::_()->getModule( 'meta' )->getModel( 'meta_values' )->getMetaValueId( $metaKeyId, 'outofstock' ); $sql[ $key ] .= ' INNER JOIN @__meta_data pm ON (pm.product_id=wpf_temp.ID AND pm.key_id=' . $metaKeyId . ' AND pm.val_id!=' . $valueId . ')'; } else { $sql[ $key ] .= ' INNER JOIN ' . $wpdb->postmeta . " pm ON (pm.post_id=wpf_temp.ID AND pm.meta_key='_stock_status' AND pm.meta_value!='outofstock')"; } }*/ if ( $addSql['withCount'] && $param['isInStockOnly'] ) { $sql[ $key ] .= $stockJoin; } if ($byVariations) { $sql[ $key ] .= ' INNER JOIN ' . $wpdb->terms . ' ttt ON (ttt.term_id=tt.term_id) ' . $typeJoin; } $sql[ $key ] .= ' WHERE tt.taxonomy IN (\'' . $addSql['taxonomyList'] . '\')'; if ($byVariations) { $sql[ $key ] .= ' AND (md_type.val_id!=' . $variableMetaId . ' OR tt.taxonomy NOT IN (\'' . implode("','", array_keys($attrTaxonomyList)) . '\')' . ' OR EXISTS(SELECT 1 FROM ' . $listVariationAttributes . ' as p_childs' . ' WHERE p_childs.id=wpf_temp.id and p_childs.taxonomy=tt.taxonomy and p_childs.value=ttt.slug LIMIT 1))'; } if ( $addSql['withCount'] ) { $sql[ $key ] .= ' GROUP BY tr.term_taxonomy_id'; } } if ( FrameWpf::_()->proVersionCompare( WPF_PRO_REQUIRES, '>=' ) ) { //$termProducts = DbWpf::get( $sql ); $termProducts = ! isset( $sql['main'] ) ? array() : DbWpf::get( $sql['main'] ); if ( false === $termProducts ) { $termProducts = array(); } $termProducts = DispatcherWpf::applyFilters( 'addCustomAttributesSql', $termProducts, array( 'taxonomies' => $param['taxonomy'], 'withCount' => $param['withCount'], 'listTable' => $listTable, 'generalSettings' => $param['generalSettings'], 'currentSettings' => $param['currentSettings'] ) ); } else { $sql['main'] = DispatcherWpf::applyFilters( 'addCustomAttributesSql', $sql['main'], array( 'taxonomies' => $param['taxonomy'], 'withCount' => $param['withCount'], 'productList' => '(select id from ' . $listTable . ')', 'generalSettings' => $param['generalSettings'], 'currentSettings' => $param['currentSettings'] ) ); $wpdb->wpf_prepared_query = $sql['main']; $termProducts = $wpdb->get_results( $wpdb->wpf_prepared_query ); } $existTerms = array(); foreach ( $termProducts as $term ) { $taxonomy = $term['taxonomy']; $isCat = 'product_cat' === $taxonomy; $name = urldecode( $taxonomy ); $names[ $name ] = $taxonomy; if ( ! isset( $existTerms[ $name ] ) ) { $existTerms[ $name ] = array(); } $termId = $term['term_id']; if ( $isCat && isset( $param['only_children_category'] ) && ! in_array( (int) $termId, $param['only_children_category'], true ) ) { continue; } if ( $isCat && !empty( $param['onlyCategories'] ) ) { $found = true; foreach ($param['onlyCategories'] as $catIds) { if (!in_array( (int) $termId, $catIds, true ) ) { $found = false; break; } } if (!$found) { continue; } } $cnt = $param['withCount'] ? intval( $term['cnt'] ) : 0; $existTerms[ $name ][ $termId ] = $cnt; $parent = ( isset( $term['parent'] ) ) ? (int) $term['parent'] : 0; if ( $isCat && $param['isCalcCategory'] && $param['calcCategory'] === $parent ) { $calcCategories[ $termId ] = $cnt; } if ( 0 !== $parent ) { $children = array( $termId ); do { if ( ! isset( $existTerms[ $name ][ $parent ] ) ) { $existTerms[ $name ][ $parent ] = 0; } if ( isset( $childs[ $parent ] ) ) { array_merge( $childs[ $parent ], $children ); } else { $childs[ $parent ] = $children; } $parentTerm = get_term( $parent, $taxonomy ); $children[] = $parent; if ( $parentTerm && isset( $parentTerm->parent ) ) { $parent = $parentTerm->parent; if ( $isCat && $param['isCalcCategory'] && $param['calcCategory'] === $parent ) { $calcCategories[ $parentTerm->term_id ] = 0; } } else { $parent = 0; } } while ( 0 !== $parent ); } } if ( 'light' !== $param['mode'] && $param['withCount'] ) { foreach ( $existTerms as $taxonomy => $terms ) { $allCalc = in_array( $taxonomy, $param['forCount'], true ); $calcWithChildren = in_array( $taxonomy, $param['forCountWithChildren'], true ); if ( ! ( $allCalc || ( $param['isCalcCategory'] && 'product_cat' === $taxonomy ) || $calcWithChildren ) ) { continue; } foreach ( $terms as $termId => $cnt ) { if ( $calcWithChildren ) { $termIds = get_term_children( $termId, $names[ $taxonomy ] ); } else { if ( isset( $childs[ $termId ] ) && ( $allCalc || isset( $calcCategories[ $termId ] ) ) ) { $termIds = $childs[ $termId ]; } else { continue; } } $termIds[] = $termId; $sqlTemp = "SELECT count(DISTINCT tr.`object_id`) FROM {$listTable} AS wpf_temp INNER JOIN {$wpdb->term_relationships} AS tr ON (tr.`object_id`=wpf_temp.`ID`) INNER JOIN {$wpdb->term_taxonomy} AS wtf ON tr.`term_taxonomy_id` = wtf.`term_taxonomy_id` WHERE wtf.`term_id` IN (" . implode( ',', $termIds ) . ')'; $cnt = intval( DbWpf::get( $sqlTemp, 'one' ) ); $existTerms[ $taxonomy ][ $termId ] = $cnt; if ( isset( $calcCategories[ $termId ] ) ) { $calcCategories[ $termId ] = $cnt; } } } } if ( ! empty( $colorGroup ) && isset( $sql['color'] ) ) { $termProducts = DbWpf::get( $sql['color'] ); $existTerms = DispatcherWpf::applyFilters( 'getExistTermsColor', $existTerms, $colorGroup, $termProducts ); } return array( $existTerms, $calcCategories ); } /** * Returns additional data on minimum and maximum prices and users * * @param $args * @param $param * * @return mixed */ public function getExistsMore( $args, $param, $result ) { global $wpdb; if (!isset($result['existsPrices'])) { $result['existsPrices'] = new stdClass(); $result['existsPrices']->wpfMinPrice = 1000000000; $result['existsPrices']->wpfMaxPrice = 0; $result['existsPrices']->decimal = 0; $result['existsPrices']->dataStep = '1'; $result['existsUsers'] = array(); } $listTable = $param['listTable']; $mode = $param['calcMode']; $need = ( 'full' === $mode && !key_exists('light', $param['calcVars']) ) || 'light' === $mode; if ( $param['havePosts'] && ! empty ( $param['taxonomies']['other_names'] ) ) { foreach ( $param['generalSettings'] as $setting ) { if ( ! isset( $setting['id'] ) ) { continue; } if ( in_array( $setting['id'], $param['taxonomies']['other_names'], true ) ) { if ('wpfPrice' == $setting['id']) { $keep = $param['taxonomies']['keep_recount_price']; if ( ( !$keep && !$need ) || ( $keep && 'full' != $mode ) ) { continue; } } else if (!$need) { continue; } switch ( $setting['id'] ) { case 'wpfPrice': case 'wpfPriceRange': $listTableForPrice = $listTable; if ( isset( $args['meta_query'] ) && is_array( $args['meta_query'] ) ) { $issetArgsPrice = false; foreach ( $args['meta_query'] as $key => $row ) { if ( isset( $row['price_filter'] ) ) { $issetArgsPrice = true; unset ( $args['meta_query'][ $key ] ); } } if ( $issetArgsPrice ) { $filterLoop = new WP_Query( $args ); if ( $filterLoop->have_posts() ) { $listTableForPrice = $this->createTemporaryTable( $this->tempFilterTable . '_price', $filterLoop->request ); } } } list( $result['existsPrices']->decimal, $result['existsPrices']->dataStep ) = DispatcherWpf::applyFilters( 'getDecimal', array( 0, 1 ), $setting['settings'] ); if ( 'wpfPriceRange' === $setting['id'] ) { $price = $this->getView()->wpfGetFilteredPriceFromProductList( $setting['settings'], $listTableForPrice, false, $result['existsPrices']->decimal ); } else { $price = $this->getView()->wpfGetFilteredPriceFromProductList( $setting['settings'], $listTableForPrice, true, $result['existsPrices']->decimal ); } if ( is_object( $price ) ) { $result['existsPrices']->wpfMinPrice = $price->wpfMinPrice; $result['existsPrices']->wpfMaxPrice = $price->wpfMaxPrice; if ( isset( $price->tax ) ) { $result['existsPrices']->tax = $price->tax; } } break; case 'wpfAuthor': case 'wpfVendors': if ( empty( $result['existsUsers'] ) ) { $query = 'SELECT DISTINCT ' . $wpdb->users . '.ID' . ' FROM ' . $listTable . ' AS wpf_temp' . ' INNER JOIN ' . $wpdb->posts . ' p ON (p.ID=wpf_temp.ID)' . ' JOIN ' . $wpdb->users . ' ON p.post_author = ' . $wpdb->users . '.ID'; $result['existsUsers'] = dbWpf::get( $query ); } break; case 'wpfAttribute': if ( false === $param['ajax'] ) { $frontendType = $this->getFilterSetting( $setting['settings'], 'f_frontend_type', '' ); if ( 'slider' === $frontendType ) { $showAllSliderAttributes = $this->getFilterSetting( $setting['settings'], 'f_show_all_slider_attributes', false ); if ( $showAllSliderAttributes ) { $this->clauses = array(); $name = $setting['name']; $data = ReqWpf::get( 'get' ); unset( $data[ $name ] ); $args['meta_query'] = DispatcherWpf::applyFilters( 'addCustomMetaQueryPro', $args['meta_query'], $data, 'url' ); $filterLoop = new WP_Query( $args ); if ( $filterLoop->have_posts() ) { $listTable = $this->createTemporaryTable( $this->tempFilterTable . '_attribute', $filterLoop->request ); if ( ! empty( $listTable ) ) { list( $existsTerms, $calcCategories ) = $this->getTerms( $listTable, $param, $result['exists'] ); $customPrefixes = DispatcherWpf::applyFilters( 'getCustomPrefixes', array(), false ); foreach ( $customPrefixes as $prefix ) { if ( strpos( $name, $prefix ) === 0 ) { $name = str_replace( $prefix, '', $name ); } } if ( isset( $existsTerms[ $name ] ) ) { $result['exists'][ $name ] = $existsTerms[ $name ]; } } } } } } break; } } } } return $result; } public function addAjaxFilterForYithWoocompare( $actions ) { return array_merge( $actions, array( 'filtersFrontend' ) ); } public function getAllPages() { global $wpdb; $allPages = dbWpf::get( "SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'page' AND post_status IN ('publish','draft') ORDER BY post_title" ); $pages = array(); if ( ! empty( $allPages ) ) { foreach ( $allPages as $p ) { $pages[ $p['ID'] ] = $p['post_title']; } } return $pages; } public function isWcVendorsPluginActivated() { return class_exists( 'WC_Vendors' ); } /** * Get logic for filtering. * * @return array */ public function getAttrFilterLogic( $mode = '' ) { $logic = array( 'display' => array( 'and' => 'And', 'or' => 'Or', ), 'loop' => array( 'and' => 'AND', 'or' => 'IN', ), 'delimetr' => array( 'and' => ',', 'or' => '|', ) ); $logic = DispatcherWpf::applyFilters( 'getAttrFilterLogic', $logic ); return empty( $mode ) ? $logic : ( isset( $logic[ $mode ] ) ? $logic[ $mode ] : array() ); } public function getFilterTagsList() { return array( 0 => 'Default', 1 => 'h1', 2 => 'h2', 3 => 'h3', 4 => 'h4', 5 => 'h5' ); } public function getCategoriesDisplay( $tax = 'product_cat' ) { $catArgs = array( 'taxonomy' => $tax, 'orderby' => 'name', 'order' => 'asc', 'hide_empty' => false, ); $productCategories = get_terms( $catArgs ); $categoryDisplay = array(); $parentCategories = array(); if (is_array($productCategories)) { foreach ( $productCategories as $c ) { if ( 0 == $c->parent ) { array_push( $parentCategories, $c->term_id ); } $categoryDisplay[ $c->term_id ] = '[' . $c->term_id . '] ' . $c->name; } } return array( $categoryDisplay, $parentCategories ); } public function getTagsDisplay() { $tagArgs = array( 'taxonomy' => 'product_tag', 'orderby' => 'name', 'order' => 'asc', 'hide_empty' => false, 'parent' => 0 ); $productTags = get_terms( $tagArgs ); $tagsDisplay = array(); if ( is_array( $productTags ) ) { foreach ( $productTags as $t ) { $tagsDisplay[ $t->term_id ] = $t->name; } } return array( $tagsDisplay ); } public function getAttributesDisplay( $withCustom = true ) { $productAttr = function_exists('wc_get_attribute_taxonomies') ? wc_get_attribute_taxonomies() : array(); if ($withCustom) { $productAttr = DispatcherWpf::applyFilters( 'addCustomAttributes', $productAttr ); } $attrDisplay = array( 0 => esc_html__( 'Select...', 'woo-product-filter' ) ); $attrTypes = array(); $attrNames = array(); foreach ( $productAttr as $attr ) { $attrId = (int) $attr->attribute_id; $slug = empty( $attrId ) ? $attr->attribute_slug : $attrId; $attrDisplay[ $slug ] = $attr->attribute_label; $attrTypes[ $slug ] = isset( $attr->custom_type ) ? $attr->custom_type : ''; $attrNames[ $slug ] = isset( $attr->filter_name ) ? $attr->filter_name : 'wpf_filter_' . $attr->attribute_name; } return array( $attrDisplay, $attrTypes, $attrNames ); } public function getRolesDisplay() { if ( ! function_exists( 'get_editable_roles' ) ) { require_once ABSPATH . '/wp-admin/includes/user.php'; } $rolesMain = get_editable_roles(); $roles = array(); foreach ( $rolesMain as $key => $r ) { $roles[ $key ] = $r['name']; } return array( $roles ); } /** * Exlude parent terms from term list * * @param array $termList * @param string $taxonomy * * @return array */ public function exludeParentTems( $termList, $taxonomy ) { foreach ( $termList as $key => $termId ) { $parents = get_ancestors( $termId, $taxonomy, 'taxonomy' ); if ( is_array( $parents ) ) { // remove all parent termsId from main parent list foreach ( $parents as $parentId ) { if ( array_search( $parentId, $termList ) !== false ) { $keyParent = array_search( $parentId, $termList ); unset( $termList[ $keyParent ] ); } } } } return $termList; } /** * Exlude parent terms from term list * * @param array $termList * @param string $taxonomy * * @return array */ public function exludeChildTems( $termList, $taxonomy ) { foreach ( $termList as $key => $termId ) { $children = get_term_children( $termId, $taxonomy ); if ( is_array( $children ) ) { // remove all parent termsId from main parent list foreach ( $children as $childId ) { if ( array_search( $childId, $termList ) !== false ) { $keyParent = array_search( $childId, $termList ); unset( $termList[ $keyParent ] ); } } } } return $termList; } /** * Add shortcode attributes to additional html data attributes * * @param array $attributes */ public function addWoocommerceShortcodeQuerySettings( $attributes ) { $shortcodeAttr = htmlentities( UtilsWpf::jsonEncode( $attributes ), ENT_COMPAT ); echo ''; } public static function getProductsShortcode( $content ) { $shortcode_tags = array( 'products' => 'WC_Shortcodes::products', 'sale_products' => 'WC_Shortcodes::sale_products', ); $original = $content; if (empty($content)) { $id = get_the_ID(); if ($id) { $p = get_post($id); if ($p) { $content = $p->post_content; } } } if ( false === strpos( $content, '[' ) ) { return $original; } if ( empty( $shortcode_tags ) || ! is_array( $shortcode_tags ) ) { return $original; } preg_match_all( '@\[([^<>&/\[\]\x00-\x20=]++)@', $content, $matches ); $tagnames = array_intersect( array_keys( $shortcode_tags ), $matches[1] ); if ( empty( $tagnames ) ) { // some themes hide woocommerce shortcodes inside their shortcodes, // so there is nothing left to do but let them run for execution $theme = wp_get_theme(); if ( $theme instanceof WP_Theme ) { $themeName = ( '' !== $theme['Parent Theme'] ) ? $theme['Parent Theme'] : $theme['Name']; if ( 'Divi' === $themeName ) { //add_filter( 'pre_do_shortcode_tag', array( 'WoofiltersWpf', 'getOtherShortcodeAttr' ), 10, 3 ); add_filter( 'pre_do_shortcode_tag', function ( $return, $tag, $attr ) { if ( 'et_pb_shop' === $tag ) { if ( isset( $attr['module_class'] ) && '' !== $attr['module_class'] ) { self::$otherShortcodeAttr['class'] = $attr['module_class']; } else { unset( self::$otherShortcodeAttr['class'] ); } } return $return; }, 10, 3 ); preg_match_all( '@(\[et_pb_shop.*?\/et_pb_shop\])@', $content, $diviShortCodes ); if ( isset( $diviShortCodes[1] ) ) { foreach ( $diviShortCodes[1] as $diviShortCode ) { do_shortcode( $diviShortCode ); } } } else if ('Shoptimizer' === $themeName) { preg_match_all( '@(\[elementor-template.*?\])@', $content, $elementorTemplates ); if ( isset( $elementorTemplates[1] ) ) { foreach ( $elementorTemplates[1] as $elementorTemplate) { do_shortcode( $elementorTemplate); } } } } return $original; } $pattern = get_shortcode_regex( $tagnames ); preg_match_all( "/$pattern/", $content, $matches ); if ( count( $matches ) > 3 ) { foreach ( (array) $matches[3] as $key => $m ) { if ( 'sale_products' === $matches[2][ $key ] ) { $m .= ' on_sale="true"'; } new WC_Shortcode_Products( shortcode_parse_atts( $m ), 'products' ); } } return $original; } public function queryResults( $result ) { if ( 0 === $result->total ) { $options = FrameWpf::_()->getModule( 'options' )->getModel( 'options' )->getAll(); if ( isset( $options['not_found_products_message'] ) && '1' === $options['not_found_products_message']['value'] ) { echo '

' . esc_html__( 'No products were found matching your selection.', 'woocommerce' ) . '

'; } } return $result; } public function getElementorClass( $data ) { $rawData = $data->get_raw_data(); if ( isset( $rawData['settings']['_css_classes'] ) && '' !== $rawData['settings']['_css_classes'] ) { self::$currentElementorClass = $rawData['settings']['_css_classes']; } } public function shortcodeAttsProducts( $out, $pairs, $atts ) { if ( isset( $atts['on_sale'] ) && ! isset( $out['on_sale'] ) ) { $out['on_sale'] = $atts['on_sale']; } $out['cache'] = false; return $out; } public function addWpfMetaClauses( $params ) { if ( empty( $params['values'] || $params['keyId'] ) ) { return; } global $wpdb; $isLight = empty( $params['isLight'] ) ? false : $params['isLight']; $isAnd = isset( $params['isAnd'] ) && true === $params['isAnd']; $isBetween = isset( $params['isAnd'] ) && 'BETWEEN' === $params['isAnd']; $keyId = $params['keyId']; $field = empty( $params['field'] ) ? 'id' : $params['field']; $values = UtilsWpf::controlNumericValues( $params['values'], $field ); $i = 0; $clauses = array( 'join' => array(), 'where' => array() ); if (empty($params['searchLogic'])) { foreach ( $values as $val ) { $i ++; $clauses['join'][ $i ] = ' INNER JOIN ' . DbWpf::getTableName( 'meta_data' ) . ' AS wpf_meta__#i ON (wpf_meta__#i.product_id=' . $wpdb->posts . '.ID AND wpf_meta__#i.key_id' . ( is_array( $keyId ) ? ' IN (' . implode( ',', $keyId ) . ')' : '=' . $keyId ) . ')'; $clauses['where'][$i] = ' AND wpf_meta__#i.val_' . $field . ( $isAnd ? '=' . $val : ( $isBetween ? ' BETWEEN ' . ( empty( $values[0] ) ? 0 : $values[0] ) . ' AND ' . ( empty( $values[1] ) ? 0 : $values[1] ) : ' IN (' . implode( ',', $values ) . ')' ) ); if ( ! $isAnd ) { break; } } } else { $i ++; $clauses['join'][ $i ] = ' INNER JOIN ' . DbWpf::getTableName( 'meta_data' ) . ' AS wpf_meta__#i ON (wpf_meta__#i.product_id=' . $wpdb->posts . '.ID AND wpf_meta__#i.key_id' . ( is_array( $keyId ) ? ' IN (' . implode( ',', $keyId ) . ')' : '=' . $keyId ) . ')' . ' INNER JOIN ' . DbWpf::getTableName( 'meta_values' ) . ' AS wpf_meta_values__#i ON (wpf_meta_values__#i.id=wpf_meta__#i.val_id)'; $clauses['where'][$i] = ' AND wpf_meta_values__#i.value+0' . $params['searchLogic'] . $params['values'][0]; } $this->addFilterClauses( $clauses, $isLight, $params['urlParam'] ); return; } public function getOtherShortcodeAttr( $return, $tag, $attr ) { if ( 'et_pb_shop' === $tag ) { if ( isset( $attr['module_class'] ) && '' !== $attr['module_class'] ) { self::$otherShortcodeAttr['class'] = $attr['module_class']; } else { unset( self::$otherShortcodeAttr['class'] ); } } return $return; } public function getFilterLoopFromMode( $mode, $args ) { $clauses = $this->clauses; if ( 'full' === $mode ) { foreach ( $this->clausesByParam as $mode => $clausesMode ) { if ( 'variation' !== $mode ) { foreach ( $clausesMode as $key => $clausesRemove ) { if ( isset( $this->clauses[ $key ] ) ) { $this->clauses[ $key ] = array_diff( $this->clauses[ $key ], $clausesRemove ); } } } } } elseif ( isset( $this->clausesByParam[ $mode ] ) ) { foreach ( $this->clausesByParam[ $mode ] as $key => $clausesRemove ) { if ( isset( $this->clauses[ $key ] ) ) { $this->clauses[ $key ] = array_diff( $this->clauses[ $key ], $clausesRemove ); } } } $filterLoop = new WP_Query( $args ); $this->clauses = $clauses; return $filterLoop; } public function getTaxonomyByUrl( $param ) { $taxonomy = null; $param = preg_replace( '/(_\d+)$/', '', $param ); if ( 0 === strpos( $param, 'wpf_filter_cat_' ) ) { $taxonomy = 'product_cat'; } elseif ( 0 === strpos( $param, 'product_tag_' ) ) { $taxonomy = 'product_tag'; } elseif ( 0 === strpos( $param, 'wpf_filter_pwb.' ) ) { $taxonomy = 'pwb-brand'; } elseif ( 0 === strpos( $param, 'fmeta-' ) ) { $taxonomy = $param; } elseif ( 0 === strpos( $param, 'wpf_filter_' ) ) { $taxonomy = preg_replace( '/^wpf_filter_/', 'pa_', $param ); } return $taxonomy; } public function getDefaultSettings() { $defaults = array( 'force_theme_templates' => '' ); return DispatcherWpf::applyFilters('getDefaultSettings', $defaults); } }