• Resolved renaldimedia

    (@renaldimedia)


    I try to create function to create or update options if attribute exists

    here my latest code :

    public function create_product_attributes($product, $variations)
    {
    if (!$product) {
    return false;
    }

    $product_id = $product->get_id();
    $existing_attributes = $product->get_attributes();
    error_log(print_r(['variations' => $variations], true));

    error_log(print_r(['existing_attributes_raw' => $existing_attributes], true));

    // Map existing attributes by taxonomy
    $existing_attr_map = [];
    foreach ($existing_attributes as $attribute) {
    $existing_attr_map[$attribute->get_name()] = $attribute;
    }

    error_log(print_r(['existing_attributes' => $existing_attr_map], true));

    foreach ($variations as $variation) {
    $code = sanitize_title($variation['code']);
    $name = $variation['name'];
    $taxonomy = lavenka_ensure_attribute($code); // pastikan taxonomy ada

    // Pastikan term ada di global taxonomy
    // 🔁 FIX: pastikan kita tidak secara keliru membuat term bernama angka.
    // Jika $name numeric: coba treat sebagai ID. Jika non-numeric: cari by name, jika tidak ada baru buat.
    $term_id = 0;

    if (is_numeric($name)) {
    // kemungkinan $name sudah berupa term ID (terjadi di runs sebelumnya)
    $maybe = get_term(intval($name), $taxonomy);
    if ($maybe && !is_wp_error($maybe)) {
    $term_id = intval($maybe->term_id);
    } else {
    // kalau tidak ada term dengan ID itu, coba cari nama (fallback)
    $maybe_by_name = get_term_by('name', (string) $name, $taxonomy);
    if ($maybe_by_name && !is_wp_error($maybe_by_name)) {
    $term_id = intval($maybe_by_name->term_id);
    } else {
    // jangan wp_insert_term dengan angka sebagai nama; treat as string fallback
    $inserted = wp_insert_term((string) $name, $taxonomy);
    if (!is_wp_error($inserted) && isset($inserted['term_id'])) {
    $term_id = intval($inserted['term_id']);
    }
    }
    }
    } else {
    // normal case: nama string
    $maybe = get_term_by('name', $name, $taxonomy);
    if ($maybe && !is_wp_error($maybe)) {
    $term_id = intval($maybe->term_id);
    } else {
    $inserted = wp_insert_term($name, $taxonomy);
    if (!is_wp_error($inserted) && isset($inserted['term_id'])) {
    $term_id = intval($inserted['term_id']);
    }
    }
    }

    error_log(print_r(['term_to_add' => $term_id, 'orig_name' => $name], true));


    // Kaitkan produk ke term (supaya muncul di filter / editor)
    $set_terms = wp_set_object_terms($product_id, [$term_id], $taxonomy, true);

    if (is_wp_error($set_terms)) {
    error_log("Ada error saat set term to object");
    }

    if (isset($existing_attr_map[$taxonomy])) {
    // Update attribute yang sudah ada
    $attribute = $existing_attr_map[$taxonomy];

    // 🔧 FIX: konversi per-option agar string term name ("Merah") dikonversi ke term_id.
    // jangan langsung intval() semua karena itu mengubah "Merah" -> 0.
    $raw_options = $attribute->get_options();
    $options = [];

    foreach ($raw_options as $opt) {
    if (is_numeric($opt)) {
    // opt mungkin sudah berupa id; pastikan ada
    $term_obj = get_term(intval($opt), $taxonomy);
    if ($term_obj && !is_wp_error($term_obj)) {
    $options[] = intval($term_obj->term_id);
    }
    } else {
    // opt disimpan sebagai nama (misal "Merah") — cari term id berdasarkan name
    $term_by_name = get_term_by('name', (string) $opt, $taxonomy);
    if ($term_by_name && !is_wp_error($term_by_name)) {
    $options[] = intval($term_by_name->term_id);
    } else {
    // kalau namanya belum ada di taxonomy, buat baru dan ambil id (aman)
    $ins = wp_insert_term((string) $opt, $taxonomy);
    if (!is_wp_error($ins) && isset($ins['term_id'])) {
    $options[] = intval($ins['term_id']);
    }
    }
    }
    }
    // bersihkan & unikkan
    $options = array_values(array_unique(array_filter($options, fn($v) => $v > 0)));

    if (!in_array($term_id, $options, true)) {
    $options[] = $term_id;
    }

    // sinkronkan relasi produk → gunakan daftar term IDs final ($options)
    if (!empty($options)) {
    // GANTI relasi product ke seluruh options yang valid (replace)
    wp_set_object_terms($product_id, $options, $taxonomy, false);
    }

    $options = array_map('intval', $options);


    error_log(print_r(['new_options_existing_attributes_' . $taxonomy => $options], true));
    $attribute->set_options($options);
    // 🔑 Tambahan penting → jaga flag tetap benar
    $attribute->set_position(0);
    $attribute->set_visible(true);
    $attribute->set_variation(true);

    $existing_attributes[$taxonomy] = $attribute;
    error_log(print_r(['existing_attributes_after_add_opt' => $existing_attributes[$taxonomy]], true));
    } else {
    // Buat attribute baru di produk
    $attribute = new WC_Product_Attribute();
    $attribute->set_id(0);
    $attribute->set_name($taxonomy);
    $attribute->set_options([$term_id]);
    $attribute->set_position(0);
    $attribute->set_visible(true);
    $attribute->set_variation(true);

    $existing_attributes[$taxonomy] = $attribute;
    error_log(print_r(['existing_attributes_after_update_opt' => $existing_attributes[$taxonomy]], true));
    }
    }

    $product->set_attributes($existing_attributes);
    $product->save();

    wc_delete_product_transients($product->get_id());


    return true;
    }

    When i create new attributes with new option, its working, but when i want update existing attribute, in global attribute it updated with no error but in product level, the attribute is not being updated

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Support shahzeen(woo-hc)

    (@shahzeenfarooq)

    Hi there!

    Thank you for sharing the details of the issue you’re facing. I understand you’re trying to programmatically create or update product attributes and their options.

    That said, this goes beyond the default functionality of WooCommerce and falls into the realm of custom development. We’re not able to provide support for custom code or customizations here.

    If you need more in-depth support or want to consider professional assistance for customization, I can recommend WooExperts and Codeable.io as options for getting professional help. Alternatively, you can also ask your development questions in the  WooCommerce Community Slack

    Plugin Support thelmachido a11n

    (@thelmachido)

    It’s been a while since we heard back from you for this reason we are closing this thread. 

    If WooCommerce has been useful for your store and you appreciate the support you’ve received, we’d truly appreciate it if you could leave us a quick review here: 

    https://wordpress.org/support/plugin/woocommerce/reviews/#new-post

    Feel free to open a new forum topic if you run into any other problem. 

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Update attribute values or options’ is closed to new replies.