Как программно создавать атрибуты и добавлять их значения для товаров в WooCommerce
Программно добавляются товары в WooCommerce, необходимо что бы еще добавлялись атрибуты и их значения для товаров. Написал такой код:
private function _product_set_attributes($product_id, $_params)
{
if (count($_params)) {
foreach ($_params as $_param) {
$_param_atts = $_param->attributes();
$_name = (string) $_param_atts->name;
$_pa_name = 'pa_' . wc_sanitize_taxonomy_name($_name);
$_value = (string) $_param;
$term_taxonomy_ids = wp_set_object_terms( $product_id, $_value, $_pa_name, true );
if ( is_wp_error($term_taxonomy_ids) ) {
$attribute_id = wc_create_attribute(array(
'name' => $_name,
));
if (!is_wp_error($attribute_id)) {
$term_taxonomy_ids = wp_set_object_terms( $product_id, $_value, $_pa_name, true );
}
}
$_attributes[$_name] = array(
'name'=>$_pa_name,
'value'=>$_value,
'is_visible' => '1',
'is_variation' => '1',
'is_taxonomy' => '1'
);
}
if (is_array($_attributes) and count($_attributes)) {
update_post_meta( $product_id, '_product_attributes', $_attributes);
}
}
}
атрибуты создаются - только дублируются - видимо нужно добавить проверку на существование атрибуты чтобы не добавлять его еще раз, так же у товаров проставляются эти атрибуты но без указанных значений
поделитесь кодом или подскажите что я не так сделал?
Ответы (2 шт):
Автор решения: WP Punk
→ Ссылка
Для добавления аттрибутов к товару во первых вам надо работать с товаром WC_Product и добавлять к нему массив аттрибутов WC_Product_Attribute. Это выглядит как-то так:
$product = new WC_Product( $product_id );
// Example attributes.
$attributes = [
'attr1' => 'Attr name',
'attr2' => 'Attr name',
]
foreach ( $attributes as $attribute => $option ) {
$pa = new WC_Product_Attribute();
$pa->set_name( sanitize_text_field( $attribute ) );
$pa->set_options( [ $option ] );
$pa->set_visible( true );
$attributes[ $attribute ] = $pa;
}
$product->set_attributes( array_values( $attributes ) );
$product->save();
Автор решения: BlackRockShooter
→ Ссылка
Для меня сработал этот код
$updated_attributes = array(
'pa_bpm' => array(124),
'pa_daw' => array('Fl stydio')
);
$product_attributes = array();
foreach ($updated_attributes as $taxonomy => $terms) {
$term_ids = array();
foreach ($terms as $term) {
$term_id = wp_set_object_terms($product->get_id(), $term, $taxonomy, true);
if (!is_wp_error($term_id)) {
$term_ids[] = $term_id[0];
}
}
foreach ($updated_attributes as $taxonomy => $terms) {
$product_attributes[$taxonomy] = array(
'name' => $taxonomy,
'value' => implode(',', $term_ids),
'is_visible' => '1',
'is_variation' => '0',
'is_taxonomy' => '1'
);
}
}
$tmpBk = get_post_meta($product->get_id(), '_product_attributes', true)
? get_post_meta($product->get_id(), '_product_attributes', true) : [];
update_post_meta($product->get_id(), '_product_attributes', array_merge($tmpBk, $product_attributes));
Надеюсь кому-то поможет