在Woocommerce中将第一个数组值设置为默认属性

时间:2018-12-24 04:59:45

标签: php wordpress woocommerce

我正在使用Woocommerce通过我自己的php以编程方式插入产品,以插入变化形式,而我正在使用update_post_meta来插入变化形式:

// set variation
    $data = array (
        "ukuran" => "S,M,L,XL",
        "price" => 100000
    );

    if (isset($data['ukuran']) && count(explode(",", $data['ukuran'])) > 1){
        $attr_label = 'Ukuran';
        $attr_slug = sanitize_title($attr_label);

        $att_ukuran = str_replace(',', '|', $data['ukuran']);
        $attributes_array[$attr_slug] = array(
            'name' => $attr_label,
            'value' => $att_ukuran, // example : "a|b|c"
            'is_visible' => '1',
            'is_variation' => '1',
            'is_taxonomy' => '0' // for some reason, this is really important       
        );
        update_post_meta( $post_id, '_product_attributes', $attributes_array );

        $parent_id = $post_id;
        $variation = array(
            'post_title'   => $article_name . ' (variation)',
            'post_content' => '',
            'post_status'  => 'publish',
            'post_parent'  => $parent_id,
            'post_type'    => 'product_variation'
        );

        foreach(explode(",", $data['ukuran']) as $new_ukuran){
            $variation_id = wp_insert_post( $variation );
            update_post_meta( $variation_id, '_regular_price', $data['price'] );
            update_post_meta( $variation_id, '_price', $data['price'] );
            // update_post_meta( $variation_id, '_stock_qty', 10 );
            update_post_meta( $variation_id, 'attribute_' . $attr_slug, $new_ukuran );
            WC_Product_Variable::sync( $parent_id );
        }
    }

但是我想为其设置默认变量,我该怎么做?我尝试

update_post_meta( $post_id, '_default_attributes', $attributes_array);

但无法正常工作,我尝试了很多次,但失败了。

0 个答案:

没有答案