I am trying to filter my products using craft commerce.
Is there a way to do craft.commerce.products.search("(field_color:red ORfield_color:blue) (field_size:S ORfield_size:M OR field_size:XXL)")
Or any other solution can help me achieve this filter.
Here is my code:
{% set productNumber = 12 %}
{% set priceMin = 0 %}
{% set priceMax = 1000 %}
{% set query = "(field_color:red OR field_color:blue) (field_size:S OR field_size:M OR field_size:XXL)" %}
{% set product_array = craft.commerce.products({
type:typeArray|default(""),
order:sort|default(""),
defaultPrice: [
'and',
'>= ' ~ priceMin,
'<= ' ~ priceMax,
]
}).search(query) %}
{% set product_array_limited = product_array.limit(productNumber|default("")) %}
{% paginate product_array_limited as product_array_pagenated %}
{% for product in product_array_pagenated %}
"Here is my product"
{% endfor %}
{% endpaginate %}
I figured out myself. I am using craft "relatedTo" Filter to Join search the content. In my system, "color" and "size" are saved as categories. In commerce product section, "color" and "size" are related to the product with "productColor" and "productSize" field.
Just like the following picture:
Product Section related Size and Color category example Image
And the category of "size" and "color" contains "title", "slug".
Size and Color in Category example Image
And in craft category, you will see the Id of that category just like the following picture.
Here is my code:
{% set colorArray = ["blue","black"] %}
{% set sizeArray = ["s","28"] %}
{% set colorId = [] %}
{% for color in colorArray %}
{% set colorId = colorId | merge(craft.categories.slug(color).Ids()) %}
{% endfor %}
{% set sizeId = [] %}
{% for size in sizeArray %}
{% set sizeId = sizeId | merge(craft.categories.slug(size).Ids()) %}
{% endfor %}
{% set IdMerge = craft.customcode.mergeArrayRemoveRedundancy(colorId,sizeId) %}
{% set productNumber = 12 %}
{% set priceMin = 0 %}
{% set priceMax = 1000 %}
{% set product_array = craft.commerce.products({
type:typeArray|default(""),
order:sort|default(""),
defaultPrice: [
'and',
'>= ' ~ priceMin,
'<= ' ~ priceMax,
]
}).relatedTo(IdMerge) %}
{% for product in product_array_pagenated %}
{# Your product #}
{% endfor %}
Here is the PHP class of "mergeArrayRemoveRedundancy" function in my "customcode" plugin.
/**
* merge array remove redundancy
* @param $a1 array
* @param $a2 array
* @return array
*/
public function mergeArrayRemoveRedundancy($a1,$a2){
$a1 = (array)$a1;
$a2 = (array)$a2;
return array_unique(array_merge($a1,$a2), SORT_REGULAR);
}
You can create custom craft plugin using "https://pluginfactory.io/" Just add PHP class under /yourPluginFolder/variables folder.