Add multiple product attributes to Woocommerce
P粉124890778
P粉124890778 2024-03-26 17:12:46
0
2
427

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粉124890778
P粉124890778

reply all(2)
P粉087074897

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

P粉327903045

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);
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!