I am trying to import product attributes that I have stored in an external database into woocommerce.
I relate the product by sku and obtain the woocommerce product id.
I try to first see if the attributes and values exist before creating them and then update the product.
I see that in Woocommerce > Attributes it does import the attributes and their values.
But it does not update the product or assign the corresponding attributes or values.
<?php
namespace AppControllers;
use AppModelsAPIModel;
use AutomatticWooCommerceClient;
use WebSocketClient as WebSocketClient;
require_once __DIR__ . '/../Helpers/helpers.php';
class APIController {
private $apiModel;
private $woocommerce;
private $socketUrl = 'ws://localhost:3001';
public function __construct($config) {
$this->apiModel = new APIModel($config, 'bylonfive');
$this->woocommerce = new Client(
'https://testing.informaticavaldepenas.es',
'ck_d6514382ffa614f8626ed743be67311b9bba405c',
'cs_f33f9c1e9585f07a725f0425985939fcaf40a24a',
[
'version' => 'wc/v3',
'query_string_auth' => true
]
);
}
public function showImportForm() {
include __DIR__ . '/../Views/api/import_form.php';
}
public function importProducts() {
$limit = $_POST['limit'] ?? 10;
$products = $this->apiModel->getProducts($limit);
$this->importAttributes($products);
$this->updateProductAttributes($products);
}
private function importAttributes($products) {
$client = new WebSocketClient($this->socketUrl);
foreach ($products as $product) {
$attributes = $this->extractAttributes($product['attributes']);
foreach ($attributes as $name => $value) {
$client->send(json_encode(['message' => "Importando atributo: {$name} con valor: {$value}"]));
// Obtener o crear el atributo global
$attribute_id = $this->getOrCreateAttribute($name);
// Obtener o crear el término del atributo
$term_id = $this->getOrCreateTerm($attribute_id, $value);
}
}
$client->close();
}
private function extractAttributes($attributeString) {
$attributes = [];
$pairs = explode(';', $attributeString);
foreach ($pairs as $pair) {
$parts = explode(':', $pair);
if (count($parts) == 2) {
$attributes[trim($parts[0])] = trim($parts[1]);
}
}
return $attributes;
}
private function getOrCreateAttribute($name) {
$existing_attributes = $this->woocommerce->get('products/attributes');
foreach ($existing_attributes as $attribute) {
if (strcasecmp($attribute->name, $name) == 0) {
return $attribute->id;
}
}
$data = [
'name' => $name,
'slug' => sanitize_title($name),
'type' => 'select',
'order_by' => 'menu_order',
'has_archives' => true
];
$new_attribute = $this->woocommerce->post('products/attributes', $data);
return $new_attribute->id;
}
private function getOrCreateTerm($attribute_id, $value) {
$existing_terms = $this->woocommerce->get("products/attributes/{$attribute_id}/terms");
foreach ($existing_terms as $term) {
if (strcasecmp($term->name, $value) == 0) {
return $term->id;
}
}
$data = [
'name' => $value,
'slug' => sanitize_title($value)
];
$new_term = $this->woocommerce->post("products/attributes/{$attribute_id}/terms", $data);
return $new_term->id;
}
private function updateProductAttributes($products) {
$client = new WebSocketClient($this->socketUrl);
foreach ($products as $product) {
$client->send(json_encode(['message' => "Obteniendo producto por SKU: {$product['sku']}"]));
$response = $this->woocommerce->get('products', ['sku' => $product['sku']]);
if (!empty($response)) {
$product_id = $response[0]->id;
$client->send(json_encode(['message' => "Producto encontrado: ID {$product_id}"]));
$attributes = $this->extractAttributes($product['attributes']);
$attributes_data = [];
foreach ($attributes as $name => $value) {
$client->send(json_encode(['message' => "Obteniendo atributo: {$name} con valor: {$value}"]));
$attribute_id = $this->getOrCreateAttribute($name);
$term_id = $this->getOrCreateTerm($attribute_id, $value);
$attributes_data[] = [
'id' => $attribute_id,
'name' => $name,
'option' => $value,
'visible' => true,
'variation' => false
];
}
$data = [
'attributes' => $attributes_data
];
$client->send(json_encode(['message' => "Datos a enviar para SKU {$product['sku']}: " . json_encode($data)]));
$updated_product = $this->woocommerce->put("products/{$product_id}", $data);
$client->send(json_encode(['message' => "Producto actualizado: SKU {$product['sku']}"]));
$updated_product_data = json_encode($updated_product->attributes);
$client->send(json_encode(['message' => "Atributos actualizados para SKU {$product['sku']}: {$updated_product_data}"]));
} else {
$client->send(json_encode(['message' => "Producto no encontrado para el SKU: {$product['sku']}"]));
}
}
$client->close();
}
}
function sanitize_title($title) {
$title = strtolower($title);
$title = preg_replace('/[^a-z0-9-]/', '-', $title);
$title = preg_replace('/-+/', '-', $title);
return trim($title, '-');
}
<?php
namespace AppControllers;
use AppModelsAPIModel;
use AutomatticWooCommerceClient;
use WebSocketClient as WebSocketClient;
require_once __DIR__ . '/../Helpers/helpers.php';
class APIController {
private $apiModel;
private $woocommerce;
private $socketUrl = 'ws://localhost:3001';
public function __construct($config) {
$this->apiModel = new APIModel($config, 'bylonfive');
$this->woocommerce = new Client(
'https://testing.informaticavaldepenas.es',
'ck_d6514382ffa614f8626ed743be67311b9bba405c',
'cs_f33f9c1e9585f07a725f0425985939fcaf40a24a',
[
'version' => 'wc/v3',
'query_string_auth' => true
]
);
}
public function showImportForm() {
include __DIR__ . '/../Views/api/import_form.php';
}
public function importProducts() {
$limit = $_POST['limit'] ?? 10;
$products = $this->apiModel->getProducts($limit);
$this->importAttributes($products);
$this->updateProductAttributes($products);
}
private function importAttributes($products) {
$client = new WebSocketClient($this->socketUrl);
foreach ($products as $product) {
$attributes = $this->extractAttributes($product['attributes']);
foreach ($attributes as $name => $value) {
$client->send(json_encode(['message' => "Importando atributo: {$name} con valor: {$value}"]));
// Obtener o crear el atributo global
$attribute_id = $this->getOrCreateAttribute($name);
// Obtener o crear el término del atributo
$term_id = $this->getOrCreateTerm($attribute_id, $value);
}
}
$client->close();
}
private function extractAttributes($attributeString) {
$attributes = [];
$pairs = explode(';', $attributeString);
foreach ($pairs as $pair) {
$parts = explode(':', $pair);
if (count($parts) == 2) {
$attributes[trim($parts[0])] = trim($parts[1]);
}
}
return $attributes;
}
private function getOrCreateAttribute($name) {
$existing_attributes = $this->woocommerce->get('products/attributes');
foreach ($existing_attributes as $attribute) {
if (strcasecmp($attribute->name, $name) == 0) {
return $attribute->id;
}
}
$data = [
'name' => $name,
'slug' => sanitize_title($name),
'type' => 'select',
'order_by' => 'menu_order',
'has_archives' => true
];
$new_attribute = $this->woocommerce->post('products/attributes', $data);
return $new_attribute->id;
}
private function getOrCreateTerm($attribute_id, $value) {
$existing_terms = $this->woocommerce->get("products/attributes/{$attribute_id}/terms");
foreach ($existing_terms as $term) {
if (strcasecmp($term->name, $value) == 0) {
return $term->id;
}
}
$data = [
'name' => $value,
'slug' => sanitize_title($value)
];
$new_term = $this->woocommerce->post("products/attributes/{$attribute_id}/terms", $data);
return $new_term->id;
}
private function updateProductAttributes($products) {
$client = new WebSocketClient($this->socketUrl);
foreach ($products as $product) {
$client->send(json_encode(['message' => "Obteniendo producto por SKU: {$product['sku']}"]));
$response = $this->woocommerce->get('products', ['sku' => $product['sku']]);
if (!empty($response)) {
$product_id = $response[0]->id;
$client->send(json_encode(['message' => "Producto encontrado: ID {$product_id}"]));
$attributes = $this->extractAttributes($product['attributes']);
$attributes_data = [];
foreach ($attributes as $name => $value) {
$client->send(json_encode(['message' => "Obteniendo atributo: {$name} con valor: {$value}"]));
$attribute_id = $this->getOrCreateAttribute($name);
$term_id = $this->getOrCreateTerm($attribute_id, $value);
$attributes_data[] = [
'id' => $attribute_id,
'name' => $name,
'option' => $value,
'visible' => true,
'variation' => false
];
}
$data = [
'attributes' => $attributes_data
];
$client->send(json_encode(['message' => "Datos a enviar para SKU {$product['sku']}: " . json_encode($data)]));
$updated_product = $this->woocommerce->put("products/{$product_id}", $data);
$client->send(json_encode(['message' => "Producto actualizado: SKU {$product['sku']}"]));
$updated_product_data = json_encode($updated_product->attributes);
$client->send(json_encode(['message' => "Atributos actualizados para SKU {$product['sku']}: {$updated_product_data}"]));
} else {
$client->send(json_encode(['message' => "Producto no encontrado para el SKU: {$product['sku']}"]));
}
}
$client->close();
}
}
function sanitize_title($title) {
$title = strtolower($title);
$title = preg_replace('/[^a-z0-9-]/', '-', $title);
$title = preg_replace('/-+/', '-', $title);
return trim($title, '-');
}
New contributor
GIGAFIX GO is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.