search

Home  >  Q&A  >  body text

Add multiple product attributes to Woocommerce

I have a form to submit new books to my WooCommerce site. I used to just save the book's condition as a product attribute. <​​/p>

// Set the book's condition

$condition = $_POST['condition'];
wp_set_object_terms( $product_id, $condition, 'pa_condition', true );

$att_condition = Array('pa_condition' =>Array(
       'name'=>'pa_condition',
       'value'=>$condition,
       'is_visible' => '1',
       'is_taxonomy' => '1'
     ));

update_post_meta( $product_id, '_product_attributes', $att_condition);

It's easy. Now I try to add the book author name and genre but when I copy the code it only sets the last product attribute. I know I should probably put it in a loop, but I%

P粉124890778P粉124890778241 days ago438

reply all(2)I'll reply

  • P粉087074897

    P粉0870748972024-03-27 13:25:50

    Glad you found a solution. However, the question of the original question has not been answered, and there is a simple bug in your solution that should be improved.

    Back to the original question.

    There are multiple issues with your original code.

    1. The variable naming and usage in your code contains errors. Adjust %E for the second time

      reply
      0
  • P粉327903045

    P粉3279030452024-03-27 10:23:39

    I found the solution on https://stackoverflow.com/a/45475863/12092133.

    I put the form variables into an array and then ran this foreach and it worked.

    $my_product_attributes['condition'] = $_POST['condition'];
    $my_product_attributes['genre'] = $_POST['genre'];
    $my_product_attributes['authors'] = $_POST['author'];
    
    foreach ($my_product_attributes as $key => $value) {
        $key = 'pa_' . $key;
        $attribute_values = explode(",", $value);
    
        wp_set_object_terms($product_id, $attribute_values, $key, false);
        $thedata[sanitize_title($key)] = Array(
            'name' => wc_clean($key),
            'value' => $attribute_values,
            'postion' => '0',
            'is_visible' => '1',
            'is_variation' => '0',
            'is_taxonomy' => '1'
        );
        update_post_meta($product_id, '_product_attributes', $thedata);
    }

    reply
    0
  • Cancelreply