Skip to navigation
Update WordPress WooCommerce attributes in batch via python script.
09.05.23
In this example, a list from a CSV file(product id/attribute name) get added to the product attributes ```python #! env/bin/python import json, requests import csv, time from multiprocessing import Process import redis def exists(key, list): for i in list: if i['name'] == key: return True return False def get_csv(file): c = {} with open(file, newline='') as csvfile: reader = csv.DictReader(csvfile) for i in reader: c[int(i['object_id'])] = i['name'] return c def get_products(url,user, password, page, att): r = requests.get(url,auth = (user, password),params={'per_page':100,'page':page}) for i in r.json(): if exists('Brand',i['attributes']) is False: if i['id'] in att: time.sleep(5) print("...add attributes {}".format(i['id'])) add_attribute(i['id'], i['attributes'], att[i['id']], user, password, url) def add_attribute(_id, attributes, name, user, password, _url): url = "{0}/{1}".format(_url,_id) brand = {'id': 3, 'name': 'Brand', 'position': 10, 'visible': True, 'variation': False, 'options': [name]} attributes.append(brand) data = {'attributes' :attributes} r = requests.put(url, data = json.dumps(data), auth = (user, password), headers={'content-type':'application/json'}, ) print("update producte {} - {} ".format(_id,r.status_code)) r = redis.Redis() r.flushdb() def main(): r = redis.Redis() r.flushdb() user = "ck_e4ddfe4febe7a12bb71cdb11446666666666" password="cs_c1857ea3996d3dee01efbb3c0066666666666" page = 1 url_products = 'https://foo.com/wp-json/wc/v3/products' att = get_csv("tr.csv") r = requests.get(url_products,auth = (user, password),params={'per_page':100,'page':page}) if r.status_code == 200: pages = int(r.headers["X-WP-TotalPages"]) for i in range(1,pages): print("...get page {1}/{0}".format(i, pages)) #res = get_products(url_products,user, password, i, att) p = Process(target=get_products, args=(url_products,user, password, i, att)) p.start() time.sleep(3) #break if __name__ == '__main__': main() ```
https://woocommerce.github.io/woocommerce-rest-api-docs/#products
Reply
Anonymous
Information Epoch 1713886084
Using text data files.
Home
Notebook
Contact us