Die globalen Attribute sind für mich von entscheidender Bedeutung Produktfilter ordnungsgemäß funktionieren. Wenn ich ein Produkt manuell bearbeite und auf „Attribute speichern“ klicke, ohne Änderungen vorzunehmen, werden die benutzerdefinierten Attribute automatisch in globale Attribute umgewandelt. Da ich jedoch über 14.000 Produkte habe, sind manuelle Aktualisierungen nicht möglich.
Ich möchte, dass die Attribute beim Importvorgang standardmäßig als globale Attribute zugewiesen werden.
Hier ist der Code, den ich zum Importieren von Produkten und Festlegen von Attributen verwende:
Code: Select all
$product_data = [
'regular_price' => $row[15] ?? '',
'sku' => $row[1],
'category' => $diamond_type,
'attributes' => [
'Lab' => $row[2] ?? '',
'Certificate No' => $row[3] ?? '',
'Shape' => $row[4] ?? '',
'Carat' => $row[5] ?? '',
'Tinge' => $row[21] ?? '',
],
'video_url' => $row[22] ?? '',
'certificate_url' => $row[23] ?? '',
'image_url' => $row[24] ?? '',
];
function spi_create_attributes_array($attributes)
{
$attribute_objects = [];
foreach ($attributes as $name => $value) {
if (!$value) continue; // Skip empty attributes
// Convert attribute name to global taxonomy (e.g., pa_color)
$taxonomy = 'pa_' . sanitize_title($name);
// Check if the taxonomy exists, create it if it doesn't
if (!taxonomy_exists($taxonomy)) {
$attribute_data = [
'name' => $name,
'slug' => sanitize_title($name),
'type' => 'select',
'order_by' => 'menu_order',
'has_archives' => false,
];
wc_create_attribute($attribute_data);
register_taxonomy(
$taxonomy,
'product',
['hierarchical' => false, 'show_ui' => false]
);
}
// Add the term to the global attribute taxonomy if it doesn't exist
if (!term_exists($value, $taxonomy)) {
wp_insert_term($value, $taxonomy);
}
// Get the term ID for the value
$term = get_term_by('name', $value, $taxonomy);
if ($term) {
$attribute = new WC_Product_Attribute();
$attribute->set_name($taxonomy);
$attribute->set_options([$term->name]);
$attribute->set_visible(true);
$attribute->set_variation(false);
$attribute_objects[] = $attribute;
}
}
return $attribute_objects;
}
$product = new WC_Product_Simple();
$attributes = spi_create_attributes_array($product_data['attributes']);
$product->set_attributes($attributes);
$product->save();
Global Bereits im Attribut hinzugefügt
Nach dem Speichern
Vollständiges Video
Was ich versucht habe:
- Sicherstellen, dass die Attributnamen genau mit den bereits definierten globalen Attributen übereinstimmen.
- Überprüfen, ob die Begriffe bereits in der globalen Attributkonfiguration erstellt wurden.
- Trotzdem werden Attribute immer als benutzerdefinierte Attribute hinzugefügt.
- Sie werden erst dann zu globalen Attributen, wenn ich das Produkt manuell bearbeite und auf „Attribute speichern“ klicke.
- Ich brauche eine Möglichkeit, programmgesteuert sicherzustellen, dass die Attribute werden während des Importvorgangs als globale Attribute hinzugefügt.