Forum

Thread tagged as: Question, Shop

Filter products by category

Hi All im trying to filter products by category but cant get it working

i have this

// Create an empty array ready to add our filters to
$filters = array();
$min = filter_var(perch_get('min_price'), FILTER_SANITIZE_NUMBER_INT);

if (perch_get('type')) {
    // if 'type' is on the URL, add a filter for bedrooms
    $filters[] = array(
        'filter' => 'type',
        'match'  => 'eq',
        'value'  => perch_get('type'),
    );
}

if (perch_get('category')) {
    // if 'beds' is on the URL, add a filter for bedrooms
    $filters[] = array(
        'filter' => 'category',
        'match'  => 'eq',
        'category'  => perch_get('category'),
    );
}

if (perch_get('min_price')) {
    // if 'location' is on the URL, add a filter for the location
    $filters[] = array(
        'filter' => 'price',
        'match'  => 'eqbetween',
        'value'  => $min . ', ' . perch_get('max_price'),
    );
}

// Unset the filters if none are used:
if (!count($filters)) $filters=false;

// Then get the list
    perch_shop_products([
    'template' => 'products/list_homepage.html',
    'sort'       => 'price', 
    'sort-order' => 'DESC',
    'filter'     => $filters,
]);
<section id="product_filter">
<perch:form id="filter" method="get">
    <div class="row">
    <div class="large-12 columns">
        <section class="rw-wrapper">
                <div class="rw-sentence">
                    <span>Choose your next </span>
                    <div class="rw-words rw-words-1">
                        <span>Adventure</span>
                        <span>Activity</span>
                        <span>Day Out</span>
                        <span>Venture</span>
                        <span>Experience</span>
                        <span>Trip</span>
                    </div>
                </div>
            </section>
    </div>
        <div class="large-3 columns">
            <perch:input type="select" id="category" placeholder="Category" options=",Kayaking|kayaking,Sailing|bushcraft,DofE|dofe,Archery|archery" />
        </div>
        <div class="large-3 columns">
            <perch:input type="number" id="min_price" placeholder="Min Price"/>
        </div>
        <div class="large-3 columns">
            <perch:input type="number" id="max_price" placeholder="Max Price" />
        </div>
        <div class="large-3 columns">
            <perch:input type="submit" value="Filter" class="button"/>
        </div>
    </div>
</perch:form>
</section>

Anthony Elleray

Anthony Elleray 2 points

  • 5 years ago
Drew McLellan

Drew McLellan 2638 points
Perch Support

The category option is not part of the filter set:

https://docs.grabaperch.com/docs/categories/filtering/

so the category needs to be added like products/archery

soo

if (perch_get('category')) {
    // if 'beds' is on the URL, add a filter for bedrooms
    $filters[] = array(
        'filter' => 'category',
        'category'  => 'products/' . perch_get('category'),
    );
}
Drew McLellan

Drew McLellan 2638 points
Perch Support

No, category isn't a filter.

perch_shop_products([
    'template' => 'products/list_homepage.html',
    'sort'       => 'price', 
    'sort-order' => 'DESC',
    'filter'     => $filters,
    'category' => 'products/' . perch_get('category'),
]);

Ahh i see

did filters also get fixed

i have managed to filter by min and max price at the same time just not min by its self

i now have this code


$filters = array(); $min = filter_var(perch_get('min_price'), FILTER_SANITIZE_NUMBER_INT); if ((perch_get('min_price')) OR (perch_get('max_price'))) { // if 'location' is on the URL, add a filter for the location $filters[] = array( 'filter' => 'price', 'match' => 'eqbetween', 'value' => perch_get('min_price') . ', ' . perch_get('max_price') ); } // Unset the filters if none are used: if (!count($filters)) $filters=false; // Then get the list perch_shop_products([ 'template' => 'products/list_homepage.html', 'sort' => 'price', 'sort-order' => 'DESC', 'category' => 'products/' . perch_get('category'), 'filter' => $filters, ]);

i can filter the category now so thats working

when i filter by min and max it works

when i filter using min or max it does not work

update

max_price works by its self but min price does not

Drew McLellan

Drew McLellan 2638 points
Perch Support

Can you please post your diagnostics report?

sure

Perch Runway: 2.8.31
Production mode: Production (100)
Installed apps: content (2.8.31), assets (2.8.31), categories (2.8.31), perch_forms (1.8.3), perch_shop_orders (1.0.6), perch_shop_products (1.0.6), perch_shop (1.0.6), perch_members (1.5)
DB driver: PDO
DB tables: perch2_backup_plans (0), perch2_backup_resources (0), perch2_backup_runs (0), perch2_categories (16), perch2_category_counts (0), perch2_category_sets (1), perch2_collection_index (0), perch2_collection_items (1), perch2_collection_revisions (1), perch2_collections (0), perch2_content_index (0), perch2_content_items (0), perch2_content_regions (13), perch2_forms (0), perch2_forms_responses (0), perch2_members (1), perch2_members_forms (2), perch2_members_member_tags (0), perch2_members_sessions (1), perch2_members_tags (1), perch2_navigation (0), perch2_navigation_pages (0), perch2_page_routes (2), perch2_page_templates (25), perch2_pages (23), perch2_resource_log (77), perch2_resource_tags (0), perch2_resources (86), perch2_resources_to_tags (0), perch2_settings (28), perch2_shop_addresses (137), perch2_shop_admin_index (24), perch2_shop_brands (1), perch2_shop_cart (71), perch2_shop_cart_data (153), perch2_shop_cart_items (64), perch2_shop_countries (250), perch2_shop_currencies (152), perch2_shop_customers (11), perch2_shop_emails (1), perch2_shop_index (526), perch2_shop_option_values (5), perch2_shop_options (1), perch2_shop_order_items (2), perch2_shop_order_promotions (1), perch2_shop_order_statuses (9), perch2_shop_orders (2), perch2_shop_orders_meta (1), perch2_shop_product_files (0), perch2_shop_product_option_values (5), perch2_shop_product_options (1), perch2_shop_product_tags (1), perch2_shop_products (11), perch2_shop_promotions (1), perch2_shop_search (6), perch2_shop_shipping_zone_countries (1), perch2_shop_shipping_zones (1), perch2_shop_shippings (1), perch2_shop_tax_exhibits (189), perch2_shop_tax_group_rates (1), perch2_shop_tax_groups (1), perch2_shop_tax_locations (1), perch2_shop_tax_rates (0), perch2_shop_variants (5), perch2_user_passwords (0), perch2_user_privileges (70), perch2_user_role_privileges (18), perch2_user_roles (3), perch2_users (2)
Users: 2
App runtimes:
<?php
    $apps_list = array(
        'content', 
        'categories',
        'perch_members',
        'perch_shop',
        'perch_forms',

    );
Editor plug-ins: markitup
H1: a2df60871efc4ba4eacb059b3a7e4197
L1: c76d5290282c2bba5a229f58a9a58e22
F1: 2edba60ed1f613d6dd804feb202456a2
headerColour: #000000
content_singlePageEdit: 1
helpURL:
siteURL: /
hideBranding: 1
content_collapseList: 1
lang: en-gb
update_2.8.29: done
headerScheme: dark
update_runway_2.8.29: done
latest_version: 2.8.15
on_sale_version: 2.8.31
dashboard: 1
hide_pwd_reset: 1
content_hideNonEditableRegions: 0
content_frontend_edit: 0
perch_members_update: 1.4
perch_members_login_page: /account/index.php?r={returnURL}
perch_shop_price_tax_mode: exc
perch_shop_trade_price_tax_mode: exc
perch_shop_site_url: https://
perch_shop_product_url: /shop/products/{slug}
perch_shop_default_currency: 47
perch_shop_reporting_currency: 47
perch_shop_update: 1.0.6
perch_shop_invoice_number_format: Order-%d
update_runway_2.8.30: done
update_runway_2.8.31: done
PERCH_DEVELOPMENT: 10
PERCH_STAGING: 50
PERCH_PRODUCTION: 100
PERCH_SITEPATH: C:\wamp64\www\harbourchallenge\perch\setup\runway\modes
PERCH_SCHEDULE_SECRET: u2xjHnOifu4ZuKb3
PERCH_DB_USERNAME: myboxpro_harbour
PERCH_DB_SERVER: 91.208.99.2
PERCH_DB_DATABASE: myboxpro_harbour
PERCH_DB_PREFIX: perch2_
PERCH_DB_PORT: 1143
PERCH_LOGINPATH: /perch
PERCH_PATH: C:\wamp64\www\harbourchallenge\perch
PERCH_CORE: C:\wamp64\www\harbourchallenge\perch\core
PERCH_RESFILEPATH: C:\wamp64\www\harbourchallenge\perch\resources
PERCH_RESPATH: /perch/resources
PERCH_HTML5: 1
PERCH_TZ: Europe/London
PERCH_DEBUG: 1
PERCH_RUNWAY: 1
PERCH_ERROR_MODE: DIE
PERCH_DATE_LONG: %d %B %Y
PERCH_DATE_SHORT: %d %b %Y
PERCH_TIME_SHORT: %H:%M
PERCH_TIME_LONG: %H:%M:%S
PERCH_RUNWAY_ROUTED:
PERCH_STRONG_PASSWORDS:
PERCH_PREVIEW_ARG: preview
PERCH_TEMPLATE_PATH: C:\wamp64\www\harbourchallenge\perch\templates
PERCH_DEFAULT_DOC: index.php
PERCH_DEFAULT_EXT: .php
PERCH_PRODUCTION_MODE: 100
PERCH_RWD:
PERCH_HTML_ENTITIES:
PERCH_SSL:
PERCH_STRIPSLASHES:
PERCH_PROGRESSIVE_FLUSH: 1
PERCH_PARANOID:
PERCH_FORCE_SECURE_COOKIES:
PERCH_PASSWORD_MIN_LENGTH: 6
PERCH_MAX_FAILED_LOGINS: 10
PERCH_AUTH_LOCKOUT_DURATION: 1 HOUR
PERCH_VERIFY_UPLOADS:
PERCH_AUTH_PLUGIN:
PERCH_DB_CHARSET: utf8
PERCH_DB_SOCKET:
PERCH_SESSION_TIMEOUT_MINS: 20
PERCH_SHOP_VERSION: 1.0.6
PERCH_APPS_EDITOR_PLUGIN: markitup
PERCH_APPS_EDITOR_MARKUP_LANGUAGE: textile
HOSTING SETTINGS

PHP: 5.6.16
Zend: 2.6.0
OS: WINNT
SAPI: apache2handler
Safe mode: not detected
MySQL client: mysqlnd 5.0.11-dev - 20120503 - $Id: 3c688b6bbc30d36af3ac34fdd4b7b5b787fe5555 $
MySQL server: 5.6.21
Free disk space: 78.75 GB
Extensions: Core, bcmath, calendar, ctype, date, ereg, filter, ftp, hash, iconv, json, mcrypt, SPL, odbc, pcre, Reflection, session, standard, mysqlnd, tokenizer, zip, zlib, libxml, dom, PDO, bz2, SimpleXML, wddx, xml, xmlreader, xmlwriter, apache2handler, openssl, curl, com_dotnet, fileinfo, gd, gettext, gmp, intl, imap, ldap, mbstring, exif, mysql, mysqli, Phar, pdo_mysql, pdo_sqlite, soap, sockets, sqlite3, xmlrpc, xsl, mhash, Zend OPcache, xdebug
GD: Yes
ImageMagick: No
PHP max upload size: 2M
PHP max form post size: 8M
PHP memory limit: 128M
Total max uploadable file size: 2M
Resource folder writeable: Yes
Session timeout: 24 minutes
Native JSON: Yes
Filter functions: Yes
Transliteration functions: Yes
HTTP_HOST: harbourchallenge.dev
HTTP_CONNECTION: keep-alive
HTTP_UPGRADE_INSECURE_REQUESTS: 1
HTTP_USER_AGENT: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36
HTTP_ACCEPT: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
HTTP_REFERER: https://harbourchallenge.dev/perch/core/settings/diagnostics/
HTTP_ACCEPT_ENCODING: gzip, deflate, sdch
HTTP_ACCEPT_LANGUAGE: en-US,en;q=0.8
HTTP_COOKIE: cmsa=1; PHPSESSID=6n50o1lgrc6mhj7592nhd0tn71
PATH: C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;
SystemRoot: C:\WINDOWS
COMSPEC: C:\WINDOWS\system32\cmd.exe
PATHEXT: .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
WINDIR: C:\WINDOWS
SERVER_SIGNATURE: <address>Apache/2.4.17 (Win64) PHP/5.6.16 Server at harbourchallenge.dev Port 80</address>
SERVER_SOFTWARE: Apache/2.4.17 (Win64) PHP/5.6.16
SERVER_NAME: harbourchallenge.dev
SERVER_ADDR: 192.168.1.4
SERVER_PORT: 80
REMOTE_ADDR: 192.168.1.19
DOCUMENT_ROOT: C:/wamp64/www/harbourchallenge
REQUEST_SCHEME: http
CONTEXT_DOCUMENT_ROOT: C:/wamp64/www/harbourchallenge
SERVER_ADMIN: admin@example.com
SCRIPT_FILENAME: C:/wamp64/www/harbourchallenge/perch/core/settings/diagnostics/index.php
REMOTE_PORT: 57901
GATEWAY_INTERFACE: CGI/1.1
SERVER_PROTOCOL: HTTP/1.1
REQUEST_METHOD: GET
QUERY_STRING: extended
REQUEST_URI: /perch/core/settings/diagnostics/?extended
SCRIPT_NAME: /perch/core/settings/diagnostics/index.php
PHP_SELF: /perch/core/settings/diagnostics/index.php
REQUEST_TIME_FLOAT: 1468491283.919
REQUEST_TIME: 1468491283

Debug for just filtering by min price

Debug Message
[23] SELECT p.pagePath, pr.routePattern, pr.routeRegExp, p.pageTemplate FROM perch2_pages p LEFT JOIN perch2_page_routes pr ON p.pageID=pr.pageID ORDER BY pr.routeOrder ASC, p.pagePath ASC
Matched page: /shop, so not using routes.
Using master page: \templates\pages\shop\index.php
[1] SELECT * FROM perch2_pages WHERE pagePath='/shop' LIMIT 1
[1] SELECT * FROM perch2_shop_cart WHERE cartID=111
[1] SELECT * FROM perch2_shop_cart WHERE cartID=111
Using template: \templates\pages\attributes\default.html
Using sub-template: \templates\pages/attributes/seo.html
Using template: \templates\search\search-form.html
[21] SELECT * FROM perch2_pages WHERE pageNew=0 AND pageHidden=0 ORDER BY pageTreePosition ASC
[1] SELECT pageTreePosition FROM perch2_pages WHERE pagePath='/shop' LIMIT 1
[1] SELECT pageID FROM perch2_pages WHERE pageTreePosition IN ('000-005', '000') ORDER BY pageTreePosition DESC
Using template: \templates\navigation\level1.html
[5] Using template: \templates\navigation\level2.html
[7] Using template: \templates\navigation\level2.html
[21] SELECT * FROM perch2_pages WHERE pageNew=0 AND pageHidden=0 ORDER BY pageTreePosition ASC
[1] SELECT pageTreePosition FROM perch2_pages WHERE pagePath='/shop' LIMIT 1
[1] SELECT pageID FROM perch2_pages WHERE pageTreePosition IN ('000-005', '000') ORDER BY pageTreePosition DESC
[7] Using template: \templates\navigation\off_canvas.html
[0] SELECT setID FROM perch2_category_sets WHERE setSlug='' LIMIT 1
[13] SELECT main.* FROM perch2_categories main WHERE 1=1 AND (catSlug!='default' AND catSlug!='dofe' AND catSlug!='instructor-courses') ORDER BY catTreePosition ASC
[13] Using template: \templates\categories\test.html
[28] SELECT DISTINCT settingID, settingValue FROM perch2_settings WHERE userID=0
Using template: \templates\forms\product_filter_side_bar.html
[6] SELECT DISTINCT idx.itemID FROM perch2_shop_index idx JOIN perch2_shop_products main ON idx.itemID=main.productID AND idx.itemKey='productID' AND ((idx.indexKey='_category' AND idx.indexValue LIKE 'products/%' OR idx.indexKey='_category' AND idx.indexValue='products/'))
[6] SELECT DISTINCT idx.itemID FROM perch2_shop_index idx JOIN perch2_shop_products main ON idx.itemID=main.productID AND idx.itemKey='productID' AND ((idx.indexKey='status' AND idx.indexValue='1')) GROUP BY idx.itemID HAVING COUNT(idx.itemID)=1
[6] SELECT DISTINCT idx.itemID FROM perch2_shop_index idx JOIN perch2_shop_products main ON idx.itemID=main.productID AND idx.itemKey='productID' AND ((idx.indexKey='parentID' AND idx.indexValue='')) GROUP BY idx.itemID HAVING COUNT(idx.itemID)=1
[nil] SELECT tbl.* FROM ( SELECT idx.itemID, main.*, idx2.indexValue as sortval FROM perch2_shop_index idx JOIN perch2_shop_products main ON idx.itemID=main.productID AND idx.itemKey='productID' JOIN perch2_shop_index idx2 ON idx.itemID=idx2.itemID AND idx.itemKey='productID' AND idx2.indexKey='price' AND idx.itemID IN ('1', '2', '4', '11', '10', '3') AND idx.itemID IN ('1', '10', '11', '2', '3', '4') AND idx.itemID IN ('1', '10', '11', '2', '3', '4') WHERE 1=1 AND ((idx.indexKey='price' AND (idx.indexValue >= '150' AND idx.indexValue <= ''))) AND idx.itemID=idx2.itemID AND idx.itemKey=idx2.itemKey ) as tbl WHERE (productDeleted IS NULL) GROUP BY itemID, sortval ORDER BY sortval DESC
Using template: \templates\shop\products\list.html
Request time: 1.496
Process time: 1.4858
Memory: 7.7212
Drew McLellan

Drew McLellan 2638 points
Perch Support

What are the options you're using to create that? I can see lots of blanks, e.g.

((idx.indexKey='price' AND (idx.indexValue >= '150' AND idx.indexValue <= '')))

i just added 150 into the min price filter but left max price empty

i need the option to add a min price and/or max price

Drew McLellan

Drew McLellan 2638 points
Perch Support

Please show me a test case with the options you're using. If I guess that won't necessarily reflect what you're doing and so might not reproduce the same issue.

Left of this page is the filter

https://harbourchallenge.myboxproject.co.uk/shop

Drew McLellan

Drew McLellan 2638 points
Perch Support

Last time of asking - please show me the options you're using.

I just have this

<section id="product_filter">
<perch:form id="filter" method="get" action="/shop">
    <div class="row">
        <div class="large-3 columns">
            <perch:input type="select" id="category" options="Category|,Archery|archery,Bushcraft|bushcraft,Climbing|climbing,Clubs|clubs,Coasteering|coasteering,Duke of Edinburgh|dofe,Equipment Hire|equipment-hire,Hiking & Navigation|hiking-and-navigation,Instructor Courses|instructor-courses,Kayaking|kayaking,Mountian Biking|mountian-biking,powerboating|Powerboating,Sailing|sailing,Taster Sessions|taster-sessions,Windsurfing|windsurfing" />
        </div>
        <div class="large-3 columns">
            <perch:input type="number" id="min_price" placeholder="Min Price"/>
        </div>
        <div class="large-3 columns">
            <perch:input type="number" id="max_price" placeholder="Max Price"/>
        </div>
        <div class="large-3 columns">
            <perch:input type="submit" value="Filter" class="button blue"/>
        </div>
    </div>
</perch:form>
</section>


$filters = array(); if ((perch_get('min_price')) OR (perch_get('max_price'))) { // if 'location' is on the URL, add a filter for the location $filters[] = array( 'filter' => 'price', 'match' => 'eqbetween', 'value' => perch_get('min_price') . ', ' . perch_get('max_price') ); } if (perch_get('certificate')) { // if 'type' is on the URL, add a filter for bedrooms $filters[] = array( 'filter' => 'certificate', 'match' => 'eq', 'value' => perch_get('certificate'), ); } // Unset the filters if none are used: if (!count($filters)) $filters=false; // Then get the list perch_shop_products([ 'template' => 'products/list.html', 'sort' => 'price', 'sort-order' => 'DESC', 'category' => 'products/' . perch_get('category'), 'paginate' => 'true', 'count' => '12', 'filter' => $filters, ]);
Drew McLellan

Drew McLellan 2638 points
Perch Support

The logic here is flawed - you have no defaults if one of the values isn't set.

if ((perch_get('min_price')) OR (perch_get('max_price'))) {
                // if 'location' is on the URL, add a filter for the location
                $filters[] = array(
                    'filter' => 'price',
                    'match'  => 'eqbetween',
                    'value'  => perch_get('min_price') . ', ' . perch_get('max_price')
                );

        }

I'd suggest adding some defaults.

if ((perch_get('min_price')) OR (perch_get('max_price'))) {
                // if 'location' is on the URL, add a filter for the location
                $filters[] = array(
                    'filter' => 'price',
                    'match'  => 'eqbetween',
                    'value'  => perch_get('min_price', 0) . ', ' . perch_get('max_price', 9999999)
                );

        }