我有一個(gè)表格可以將新書提交到我的 WooCommerce 網(wǎng)站。我以前只是將書的狀況保存為產(chǎn)品屬性。 ?/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);
這很容易?,F(xiàn)在我嘗試新增圖書作者的姓名和類型,但是當(dāng)我複製程式碼時(shí),它只設(shè)定最後一個(gè)產(chǎn)品屬性。我知道我可能應(yīng)該把它放在一個(gè)循環(huán)中,但?%
很高興您找到了解決方案。但是,原始問題的問題尚未得到解答,並且您的解決方案中存在一個(gè)簡單的錯(cuò)誤,應(yīng)該予以改進(jìn)。
回到原來的問題。
您的原始程式碼存在多個(gè)問題。
您的程式碼中的變數(shù)命名和使用包含錯(cuò)誤。第二次?%8
我在https://stackoverflow.com/a/45475863/12092133上找到了解決方案。
我將表單變數(shù)放入陣列中,然後執(zhí)行這個(gè) foreach 就成功了。
$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); }