Menu
  • HOME
  • TAGS

Woocommerce Filter Product by Attribute

Tag: filter,attributes,woocommerce,product

I've been searching for many blogs and forum but this seems not yet answered yet. So i am trying to find a way how to filter product by attribute. I am using ajax to pull data and append it.The question is what will be the query to make a loop depend on what attribute.

Example.
Product A has Color:Blue,Red,Green and has a brand : BrandA , BrandB
Product B has Color:Pink,Red,black.

All i want is to get all product with an attribute of Color [red and green] and Brand [BrandA] in a single query without using any plugin. Here my code in my functions.php

function advanced_search(){

     $html = "";
     $args = array( 'post_type' => 'product','product_cat' => 'yarn');
     $loop = new WP_Query( $args );
     while ( $loop->have_posts() ){
         $loop->the_post();
         ob_start();
         get_template_part( 'templates/part', 'search-result' ); 
         $html = ob_get_contents();
         ob_end_clean();
     }  
     wp_send_json(array(  "product_id" => $product_id , "html"  => $html ));
}
add_action('wp_ajax_get_advanced_search', 'advanced_search');
add_action('wp_ajax_nopriv_get_advanced_search', 'advanced_search'); 

I dont know where should i put the product attributes in my query. I hope anyone found an answer for this.Thank you very much.

Best How To :

You should be able to achieve what you're looking to do by using a tax_query combined with your WP_Query. Attached is a small example using a 'Brand' attribute and the 'EVGA' term inside it (which WooCommerce will turn into 'pa_brand' - product attribute brand).

$query = new WP_Query( array(
    'tax_query' => array(
        'relation'=>'AND',
        array(
            'taxonomy' => 'pa_brand',
            'field' => 'slug',
            'terms' => 'evga'
        )
    )
) );

You can find some more documentation on the above links to string a few tax queries together for additional filtering and functionality.

Can I filter an Android app by the mobile network operator?

android,networking,filter,operator-keyword,carrier

Yes. While selecting the country filter you get an option to choose the network operator in the playstore console.

How to specify callback function when filtering array with object elements in php?

php,arrays,filter

You need to indicate the object as well as the method in your callback, using an array syntax as shown in the php docs for callbacks class my_class{ private $exclude; public filter_function(){ return !$this->exclude; } } $array = array($my_object1, $my_object2, ....); $classFilter = new my_class(); $filtered = array_filter($array,[$classFilter, 'filter_function']); In...

AngularJS Filter two select inputs with values less than or equal to value

javascript,angularjs,select,filter,compare

You can create an object which represents your two inputs. $scope.inputs = { 'A': 0, 'B': 0 }; Use an ng-change to call a function which checks the sum of all inputs and makes sure they are less than the max value. <select ng-model="inputs.A" ng-options="number for number in numbers" ng-change="verifySum('A');"></select>...

How to get specific value of an dictionary

c#,object,dictionary,filter

Using LINQ is the best option here. If you want access your class in regular loop, it will be like this: foreach (KeyValuePair<string, MYCLASS> entry in MyDic) { // Value is in: entry.Value and key in: entry.Key foreach(string language in ((MYCLASS)entry.Value).Language) { //Do sth with next language... } } ...

Render outcome of “action” attribute?

jsf,attributes,action,renderer

As always, BalusC was right. There is no generated Javascript. But there was another thing i forgot about. One needs to add the following code: button.queueEvent(new ActionEvent(button)); in the decode method of the according component renderer, where "button" is the UIComponent parameter of the "decode" method. Thanks a lot BalusC...

Excel VBA - ShowAllData fail - Need to know if there is a filter

excel,vba,excel-vba,filter

If you use Worksheet.AutoFilter.ShowAllData instead of Worksheet.ShowAllData it will not throw the error when nothing is filtered. This assumes that Worksheet.AutoFilterMode = True because otherwise you will get an error about AutoFilter not being an object. Public Sub UnFilter_DB() Dim ActiveS As String, CurrScreenUpdate As Boolean CurrScreenUpdate = Application.ScreenUpdating Application.ScreenUpdating...

Using this.store.filter with the ID of the belongs_to model

ember.js,filter,belongs-to

Ember Data works with all its IDs as strings. Changing your check to === '1' should get this going for you. import Ember from 'ember'; export default Ember.Route.extend({ model: function() { return Ember.RSVP.hash({ layouts: this.store.filter('layout', { account_id: 1 }, function(layout) { console.log(layout.get('account').content.id); return layout.get('account').content.id === '1'; }) }); } });...

Filter rows in R using subset

r,filter,subset

Use a regular expression. For example: myd <- subset(df, grepl("-01$", Date_ID)) or myd <- df[grep("-01$", df$Date_ID),] ...

Leverage MultipleApiVersions in Swagger with attribute versioning

attributes,asp.net-web-api2,swagger,swagger-ui,swashbuckle

.EnableSwagger(c => c.MultipleApiVersions( (apiDesc, version) => { var path = apiDesc.RelativePath.Split('/'); var pathVersion = path[1]; return CultureInfo.InvariantCulture.CompareInfo.IndexOf(pathVersion, version, CompareOptions.IgnoreCase) >= 0; }, vc => { vc.Version("v2", "Swashbuckle Dummy API V2"); //add this line when v2 is released // ReSharper disable once ConvertToLambdaExpression vc.Version("v1", "Swashbuckle Dummy API V2"); } )) ...

Add element with text from class name in jQuery

javascript,jquery,attributes

You'll need a loop, assuming there's more than one .ctnr: $(".ctnr").each(function() { var code = $("<code>").addClass("info").text($(this).find("div").attr("class")); code.prependTo(this); }); <div class="ctnr"> <div class="up-triangle"></div> </div> <div class="ctnr"> <div class="up-square"></div> </div> <div class="ctnr"> <div class="up-circle"></div> </div> <script...

Should I use a cite attribute, at its current state?

html,html5,attributes,cite

Yes, use cite, the semantic web can be ours today. Cite becomes more important the more people use it. If everyone used the attribute, developers could make some pretty awesome stuff. Using extra semantics such as these are also good for SEO. Even if Google does not currently look for...

Creating a list of items with different tags + filter

javascript,html,list,filter

Here is the codePen I have created for you with example: $('#filter').click(function() { var _typeFilter = $('input[name=type]:checked').val(); var _locationFilter = $('input[name=location]:checked').val(); $('ul li').each(function() { if ($(this).filter('[type=' + _typeFilter + ']').filter('[location=' + _locationFilter + ']').length > 0) $(this).show(); else $(this).hide(); }); }); $('#clear').click(function() { $('ul li').show(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>...

How to check if element of an array is in another array?

ios,arrays,swift,filter

I suspect you are searching for the problem in the wrong place. You code on how to search trough the array is indeed correct. var Items :[Int] = [1,2,3,4,5,6,7,8,9,] var favoriteItems:[Int] = [1,3,4,5,7] if contains(Items, favoriteItems[3]){ println("found item") }else{ println("doesnotcontains item") } Does work in swift 1.2. The fourth item...

Get every other value of array in PHP

php,arrays,filter

Try as $arr = Array ( 'A' => 4, 'B' => 4, 'D' => 4, 'E' => 8, 'F' => 4, 'G' => 8, 'H' => 8, 'J' => 12, 'K' => 12, 'L' => 11, 'M' => 11, 'O' => 10, 'P' => 10, 'Q' => 10, 'R' =>...

ACCESS 2007 - Form / subform filtering between dates

vba,date,ms-access,filter

You need proper date formatting: strFilterNaklady = "[datNakladDatum] Between #" & Format(datRokMesiacOd, "yyyy\/mm\/dd") & "# And #" & Format(datRokMesiacDo, "yyyy\/mm\/dd") & "#" Also, this can be reduced to: datRokMesiacDo = DateSerial(Year(cmbStavK), Month(cmbStavK) + 1, 0) 'end Date ...

Dynamic annotation/attribute values

c#,validation,annotations,attributes

All true. You can not. Despite you wrote you can not use enums, this actually can serve a solution: Pass enum parameter to your attribute and use this parameter in the attribute constructor's logic/algorithm to implement your extended logic. Note: This is exactly opposite of some DPs so we safely...

DOORS Compound Filter Dilemma

filter,dxl,doors

Your issue is Include Descendants. This options specifically ignores the filter. What it is really saying is, "Show me everything that matches my filter, and all of their descendants". Using your example above, what you want for a filter is: Object Number >= 1.2 and Object Number < 2 (or...

Visual Studio: replace default doubleclick-event

c#,winforms,visual-studio,events,attributes

if you just add DefaultEvent attribute to your control class with another event name, it should work fine (rebuild projects before check after adding attribute) [DefaultEvent("KeyPress")] public class NumericControl : System.Windows.Forms.NumericUpDown ...

Php filter system

php,mysql,filter

You probably just need to construct your full WHERE in advance so that instead of sending 4 vars to your query you send a single WHERE statement. Example 1 (constructing a $where var which concatenates your conditions): $where = "WHERE "; $count = 0; if ( !empty($tijd) ) { $where...

Sending a Class' attribute to an outside function in the function call

python,class,tkinter,attributes

I think what you want is def input_check(which_box): getattr(my_window,which_box).delete(0, "end") return 0 input_check("get_info_box") but its hard to tell for sure...

angularJs filter in ng-repeat

angularjs,filter,angularjs-directive

There is built-in limitTo filter doing exactly what you are trying to achieve. By the way on our projects we always ended up filtering arrays on-demand in the controller (or custom directive) so that the ngRepeat doesn't have to use any filters....

return RSS attribute values via BeautifulSoup

python,attributes,rss,beautifulsoup

Telling BeautifulSoup to use the lxml parser seems to keep self closing tags. Try using: soup = BeautifulSoup(handler, 'lxml') ...

How to retrieve filtered data from json with double for loop

javascript,json,loops,for-loop,filter

If i understood you correctly, you need to add additional for loop for all bussen for (var i=0;i<bushalte2.length;i++) { $("#bussen").append(bushalte2[i].name + "<br/>"); for (var j=0; j <bushalte2[i].bussen.length; j++) { $("#bussen").append(bushalte2[i].bussen[j].busnummer + "<br/>"); } } here is updated jsfiddle https://jsfiddle.net/or4e8t3u/...

No such column for attribute in a join table

ruby-on-rails,activerecord,attributes,associations,jointable

The error is caused by a faulty foreign_key option in TaskVolunteer. belongs_to :volunteer, class_name: "User", foreign_key: :volunteer_id foreign_key here refers to the column on the users table not on tasks_volunteers. You can just remove the foreign key option. class TaskVolunteer < ActiveRecord::Base # task_id, volunteer_id, selected (boolean) belongs_to :task belongs_to...

Excel VBA range after filtering xlCellTypeVisible

excel,vba,excel-vba,filter,range

Something like this should work: Dim newrange As Range, rw as range Set newrange = ActiveSheet.AutoFilter.Range.SpecialCells(xlCellTypeVisible) Dim intValueToFind As Integer intValueToFind = 2 For Each rw in newrange.Rows If rw.cells(3).Value = intValueToFind Then MsgBox ("Found value on row " & rw.cells(1).Row) Exit Sub End If Next rw ...

How to mark function argument as output

c++,c,gcc,attributes,out

"Is it possible to do something similar in C/C++?" Not really. Standard c++ or c doesn't support such thing like a output only parameter. In c++ you can use a reference parameter to get in/out semantics: void func(int& i) { // ^ i = 44; } For c you...

Spring boot - adding a filter

filter,spring-boot

If your Filter has a no-args constructor this should work. try { Class c = Class.forName("com.runtimeFilter"); Filter filter = (Filter)c.newInstance(); //register filter with bean } catch (Exception e) {} If it has a constructor with args you need to use the getConstructor() method on Class....

Android listview filter without pressing search button issue

android,database,listview,filter

Use the addTextChangedListener() method of your EditText. It would look something like this inputSearch = (EditText)findViewById(R.id.editText); .... .... listView.setAdapter(listDataAdapter); inputSearch.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) { // When user changes the Text listDataAdapter.getFilter().filter(cs); } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int...

Multiple filters using JQ

json,filter,jq

Always proceed with caution when using filters that uses multiple [] in a single expression. You may get unexpected results if you aren't careful. I would approach this as converting to CSV (but using a different delimiter, a tab). First convert the data to what will be your rows. .Collections[]...

How do I do to count rows in a sheets with filters? With a suppress lines

excel,vba,filter

Try the following which uses the SpecialCells() method to select only cells that are currently visible on screen (i.e. not filtered out). count = Application.WorksheetFunction.CountA(Range("A:A").SpecialCells(xlCellTypeVisible)) ...

Accessing a custom attribute from within an instanced object

c#,attributes

Attributes aren't used that way. Attributes are stored in the class object that contains the attribute, not the member object/field that is declared within the class. Since you want this to be unique per member, it feels more like this should be member data with MyField, something passed in by...

Jquery Filter Out Radio Buttons ( .not( ) )

php,jquery,filter

Use find() to grab direct/nested children var someVariable = $(question).find('*').not("input[type=radio]").html(); ...

Filter array of objects with another array of objects

javascript,jquery,arrays,object,filter

var filtered = []; for(var arr in myArray){ for(var filter in myFilter){ if(myArray[arr].userid == myFilter[filter].userid && myArray[arr].projectid == myFilter[filter].projectid){ filtered.push(myArray[arr].userid); } } } console.log(filtered); ...

jQuery link elements by attribute

jquery,attributes

You can use hover: Changes in HTML: <div id="message_3" class="tester">HAHAHAHAHAHAHA</div> ^^^^^^^^^ <div id="message_4" class="tester">Another HAHAHAHAHAHAHA</div> ^^^^^^^^^ Javascript: $('.bx').hover(function () { $(this).css("background-color", "blue"); $('#message_' + $(this).attr('id')).show(); }, function () { $(this).css("background-color", "white"); $('.tester').css("display", "none"); }); Demo: https://jsfiddle.net/tusharj/pkb3q6kq/21/ Id must be unique on the page You don't need to bind event to...

How can I filter instances of a model in django, with a queryset value of filter field?

python,django,filter

Nothing magic ModelA.objects.filter(att1=queryset of modelB) ...

Firebase: combine filtering with ordering in swift

swift,filter,order,firebase

Got it! I had already read the documentation before posting the question, but haven't had the click that lead me to the solution. This section on structuring data holds the answer: https://www.firebase.com/docs/ios/guide/structuring-data.html Understand: The natural structure would be: - champs - champID - matches - matchID - <matchData> - champName...

3 condition in WHERE clause for filtering

c#,filter

You have to use parameterized query like string query = @"SELECT DISTINCT Time, Temperature FROM Data3 WHERE (UnitNo = ?) AND (Date >= ?) AND (Date <= ?)"; And then add parameters like: ada.SelectCommand.Parameters.Add(new OleDbParameter("Unit", txtUnit.Text)); ada.SelectCommand.Parameters.Add(new OleDbParameter("DateFrom", ComboStart.Text)); ada.SelectCommand.Parameters.Add(new OleDbParameter("DateTo", ComboEnd.Text)); ...

SQL Query Filter to locate DUPLICATES in a column based on Values in 2 other columns

sql-server,filter,duplicates

You can use LEAD, LAG window functions in order to locate records that have been split: SELECT Name, MIN(ArrivalDate) AS ArrivalDate, MAX(DepartureDate) AS DepartureDate FROM ( SELECT Name, ArrivalDate, DepartureDate, CASE WHEN ArrivalDate = LAG(DepartureDate) OVER (PARTITION BY Name ORDER BY ArrivalDate) OR DepartureDate = LEAD(ArrivalDate) OVER (PARTITION BY Name...

Filter array by common object property in Angular.js?

javascript,arrays,json,angularjs,filter

Use angular-filter to do the grouping. Your view code will look like this: <ul ng-repeat="(key, value) in people | groupBy: 'city'"> City: {{ key }} <li ng-repeat="person in value"> person: {{ person.name }} </li> </ul> Here's a Plunker....

Using Python, I want to parse each file in one directory with format YY-MM-DD.CSV but ignore all others

python,regex,file,filter

Here's a function that returns whether a filename matches your YY-MM-DD.csv pattern or not. from datetime import datetime def is_dated_csv(filename): """ Return True if filename matches format YY-MM-DD.csv, otherwise False. """ date_format = '%y-%m-%d.csv' try: datetime.strptime(filename, date_format) return True except ValueError: # filename did not match pattern pass return False...

Accessing _all_ downstream annotations of a node in Rascal

attributes,rascal

This first solution is precise and useful if the number of nodes with container children is not so large: x = \anode([\bnode()[@mass=1], \bnode()[@mass=2]], \cnode()[@mass=5]); visit(x) { case n:\anode(l) => n[@mass=(0 | it + [email protected] | e <- l)] } (You'd probably also abstract the reducer expression in a local function)...

Excel Advanced Filter not working with Wildcard (* asterisk) using regular numbers and hyphenated number system

excel,filter,wildcard

You had the right idea when you tried formatting as text: wildcards don't work on numeric values. Where you're running into trouble is that formatting as text doesn't change numbers to text retroactively; only numbers entered after the format change get converted. Instead convert your data to strings first using...

Can the HTTP method “PATCH” be safely used across proxies etc.?

http,caching,filter,proxy,http-patch

The answer to this question is a moving target. As time progresses and PATCH either becomes more or less popular, the systems in the network may or may not support it. Generally only the network entities that will care about HTTP verbs will be OSI Level 3 (IP) and up...

UnderscoreJS : filter part of string

string,filter,find,underscore.js

var myArray = ["myString"]; if(myArray[0].IndexOf("my") != -1 || myArray.IndexOf("String") != -1 ) { ... } I didn't misunderstand the question, did I? Underscore.js wouldn't be required for this, either....

I need help displaying an Xml file with php in table form

php,xml,table,attributes

OK - try this one then.. $xml = simplexml_load_file($file); echo '<table>'; foreach($xml->level_1->level_2 as $item){ $level3 = $item->level_3_1->attributes(); echo '<tr>'; foreach($level3 as $name => $value){ echo "<th>$name</th>"; echo "<td>$value</td>"; } echo '</tr>'; } echo '</table>'; ...

How to filter keys of an object with lodash?

javascript,filter,lodash

Lodash has a _.pick function which does exactly what you're looking for. var thing = { "a": 123, "b": 456, "abc": 6789 }; var result = _.pick(thing, function(value, key) { return _.startsWith(key, "a"); }); console.log(result.abc) // 6789 console.log(result.b) // undefined <script src="https://cdn.rawgit.com/lodash/lodash/3.0.1/lodash.min.js"></script> ...

How to subset by distinct rows in a data frame or matrix?

r,matrix,filter,data.frame,subset

Try this: (I suspect will be faster than any apply approach) mat[ rowSums(mat == mat[,1])!=ncol(mat) , ] # ---with your object--- [,1] [,2] [,3] [1,] 1 2 3 [2,] 1 3 2 ...

Creating a status attribute for a model

ruby-on-rails,ruby,activerecord,model,attributes

Rails 4 has an built in enum macro. It uses a single integer column and maps to a list of keys. class Order enum status: [:ordered, :shipped, :delivered] end The maps the statuses as so: { ordered: 0, shipped: 1, delivered: 2} It also creates scopes and "interrogation methods". order.shipped?...

angularjs filter an array with string values as integers in contoller

arrays,angularjs,filter

Replace value with a function that returns the length of the string: $filter('orderBy')( array, function(item) { return parseInt( item.value ); } , true ); ...

XSLT sort by attribute and attribute value (with exclude)

sorting,xslt,attributes,xslt-1.0,alphabetical

I am not entirely sure if this meets your requirements, but you could explicitly select the ones you want to come first in a separate xsl:apply-templates, then select the others with a sort on their type attribute <xsl:apply-templates select="orderEntry[@type='specific' or @type='other']" /> <xsl:apply-templates select="orderEntry[@type!='specific' and @type!='other']"> <xsl:sort select="@type" order="descending" />...