Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert WooCommerce Custom Product Attributes into Defined Product Attributes

I am trying to filter ~30,000 products in a WooCommerce store using WooCommerce's Layered Nav attribute filter sidebar widget. This requires the use of a pre-defined product attribute taxonomy, as opposed to using custom attributes on a per-product basis.

Each product in the store has an imported custom 'Brand' attribute. Prior to importing products, I created an attribute taxonomy called 'Brand' (pa_brand) in wp-admin. However, imported products have not had their Brand attribute (and term name) added to the Brand (pa_brand) taxonomy. Instead, all of the products have a custom attribute called 'Brand' not linked to the pa_brand taxonomy.

Does anyone know how to convert custom product attributes into defined attributes within the pre-defined taxonomy (with terms not yet created)?

I assume that I'd need to run a PHP script which does the following, but don't know if I've missed any steps out:

  1. Obtain an array of ID's for all of the products in the database
  2. Loop over each of the product ID's (foreach)
    • get_attributes() from each product ID - this will return the custom 'Brand' attribute (there are no pa_brand assignments yet)
    • Check: If the brand term already exists in the pa_brand taxonomy, do nothing; if it doesn't, add the term to the pa_brand taxonomy
    • Assign the product to the term within the pa_brand taxonomy
    • Delete the old custom Brand product attribute

I'm not sure how best to execute this, so any help would be very much appreciated.

PS: to illustrate the distinction between 'custom attributes' and attributes defined in a taxonomy,
I have added 2 screenshots below of how they differ when editing a product in WooCommerce. Note how the name of the attribute can be altered if not from the defined taxonomy.

Attributes defined in taxonomy:

Attributes defined in taxonomy

Custom attributes:

Custom attributes

Thanks

like image 740
Jamie Avatar asked Aug 14 '16 15:08

Jamie


1 Answers

It looks like someone has done this before - https://gist.github.com/birgire/0ed300ae4436fcaf508c

like image 149
Jamie Avatar answered Oct 11 '22 13:10

Jamie