Wordpress Woocommerce - use update_post_meta to add product attributes

后端 未结 4 1117
广开言路
广开言路 2020-12-05 15:56

The products in my clients website require certain attributes which I have added via Products -> Attributes in the Wordpress administration. In this import script I\'

4条回答
  •  佛祖请我去吃肉
    2020-12-05 16:23

    Right so it took me a while to figure it out myself but I finally managed to do this by writing the following function:

    // @param int $post_id - The id of the post that you are setting the attributes for
    // @param array[] $attributes - This needs to be an array containing ALL your attributes so it can insert them in one go
    function wcproduct_set_attributes($post_id, $attributes) {
        $i = 0;
        // Loop through the attributes array
        foreach ($attributes as $name => $value) {
            $product_attributes[$i] = array (
                'name' => htmlspecialchars( stripslashes( $name ) ), // set attribute name
                'value' => $value, // set attribute value
                'position' => 1,
                'is_visible' => 1,
                'is_variation' => 1,
                'is_taxonomy' => 0
            );
    
            $i++;
        }
    
        // Now update the post with its new attributes
        update_post_meta($post_id, '_product_attributes', $product_attributes);
    }
    
    // Example on using this function
    // The attribute parameter that you pass along must contain all attributes for your product in one go
    // so that the wcproduct_set_attributes function can insert them into the correct meta field.
    $my_product_attributes = array('hdd_size' => $product->hdd_size, 'ram_size' => $product->ram_size);
    
    // After inserting post
    wcproduct_set_attributes($post_id, $my_product_attributes);
    
    // Woohay done!
    

    I hope this function will help other people if they need to import multiple attributes pro-grammatically in WooCommerce!

提交回复
热议问题