wordpress 以编程方式为可变产品设置变体默认属性值

qv7cva1a  于 2022-11-22  发布在  WordPress
关注(0)|答案(1)|浏览(177)

我正在建立一个网站,其中WooCommerce可变产品(与产品变化)被插入编程。我已经按照这个教程成功:
Insert WooCommerce Products & Variations Programmatically
我只需要缺少的东西:
如何为可变产品设置可变默认属性值?是否可行?

cbeh67ev

cbeh67ev1#

1).您需要在您的**json**数据中为每个变量积插入这段数组,如:

"variations_default_attributes":
        [
            {
                "size"  : "Medium",
                 "color" : "Blue"
            }
        ]

或者

"variations_default_attributes":
    {
        "size"  : "Medium",
        "color" : "Blue"
    }
  • 此数组由属性short slug(不含'pa_')和默认术语name值组成。*

2).然后是专用功能:

function insert_variations_default_attributes( $post_id, $products_data ){
    foreach( $products_data as $attribute => $value )
        $variations_default_attributes['pa_'.$attribute] = get_term_by( 'name', $value, 'pa_'.$attribute )->slug;
    // Save the variation default attributes to variable product meta data
    update_post_meta( $post_id, '_default_attributes', $variations_default_attributes );
}

3).您需要在末尾添加一行来触发此函数:

function insert_product ($product_data)  
{
    $post = array( // Set up the basic post data to insert for our product

        'post_author'  => 1,
        'post_content' => $product_data['description'],
        'post_status'  => 'publish',
        'post_title'   => $product_data['name'],
        'post_parent'  => '',
        'post_type'    => 'product'
    );

    $post_id = wp_insert_post($post); // Insert the post returning the new post id

    if (!$post_id) // If there is no post id something has gone wrong so don't proceed
    {
        return false;
    }

    update_post_meta($post_id, '_sku', $product_data['sku']); // Set its SKU
    update_post_meta( $post_id,'_visibility','visible'); // Set the product to visible, if not it won't show on the front end

    wp_set_object_terms($post_id, $product_data['categories'], 'product_cat'); // Set up its categories
    wp_set_object_terms($post_id, 'variable', 'product_type'); // Set it to a variable product type

    insert_product_attributes($post_id, $product_data['available_attributes'], $product_data['variations']); // Add attributes passing the new post id, attributes & variations
    insert_product_variations($post_id, $product_data['variations']); // Insert variations passing the new post id & variations

    ## Insert variations default attributes passing the new post id & variations_default_attributes
    insert_variations_default_attributes( $post_id, $products_data['variations_default_attributes'] );    
}
  • 代码在您的活动子主题(或主题)的function.php文件中,也可以在任何插件文件中。*

这段代码已经过测试并且可以正常工作。

相关问题