WordPress Woocommerce 3.1.2 - 以编程方式创建变量产品

时间:2017-11-06 09:17:21

标签: php wordpress woocommerce

在互联网上,我发现了许多创建变量产品的方法,但没有一种方法能够创造出可变的商品。在数据库中,条目与通过管理面板创建的记录不对应。请帮帮我!

WC version3.1.2
WP version4.8.3

site

的示例代码

functions.php

<?php 

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   
}

function insert_product_attributes ($post_id, $available_attributes, $variations)  
{
    foreach ($available_attributes as $attribute) // Go through each attribute
    {   
        $values = array(); // Set up an array to store the current attributes values.

        foreach ($variations as $variation) // Loop each variation in the file
        {
            $attribute_keys = array_keys($variation['attributes']); // Get the keys for the current variations attributes

            foreach ($attribute_keys as $key) // Loop through each key
            {
                if ($key === $attribute) // If this attributes key is the top level attribute add the value to the $values array
                {
                    $values[] = $variation['attributes'][$key];
                }
            }
        }

        // Essentially we want to end up with something like this for each attribute:
        // $values would contain: array('small', 'medium', 'medium', 'large');

        $values = array_unique($values); // Filter out duplicate values

        // Store the values to the attribute on the new post, for example without variables:
        // wp_set_object_terms(23, array('small', 'medium', 'large'), 'pa_size');
        wp_set_object_terms($post_id, $values, 'pa_' . $attribute);
    }

    $product_attributes_data = array(); // Setup array to hold our product attributes data

    foreach ($available_attributes as $attribute) // Loop round each attribute
    {
        $product_attributes_data['pa_'.$attribute] = array( // Set this attributes array to a key to using the prefix 'pa'

            'name'         => 'pa_'.$attribute,
            'value'        => '',
            'is_visible'   => '1',
            'is_variation' => '1',
            'is_taxonomy'  => '1'

        );
    }

    update_post_meta($post_id, '_product_attributes', $product_attributes_data); // Attach the above array to the new posts meta data key '_product_attributes'
}

function insert_product_variations ($post_id, $variations)  
{
    foreach ($variations as $index => $variation)
    {
        $variation_post = array( // Setup the post data for the variation

            'post_title'  => 'Variation #'.$index.' of '.count($variations).' for product#'. $post_id,
            'post_name'   => 'product-'.$post_id.'-variation-'.$index,
            'post_status' => 'publish',
            'post_parent' => $post_id,
            'post_type'   => 'product_variation',
            'guid'        => home_url() . '/?product_variation=product-' . $post_id . '-variation-' . $index
        );

        $variation_post_id = wp_insert_post($variation_post); // Insert the variation

        foreach ($variation['attributes'] as $attribute => $value) // Loop through the variations attributes
        {   
            $attribute_term = get_term_by('name', $value, 'pa_'.$attribute); // We need to insert the slug not the name into the variation post meta

            update_post_meta($variation_post_id, 'attribute_pa_'.$attribute, $attribute_term->slug);
          // Again without variables: update_post_meta(25, 'attribute_pa_size', 'small')
        }

        update_post_meta($variation_post_id, '_price', $variation['price']);
        update_post_meta($variation_post_id, '_regular_price', $variation['price']);
    }
}

function insert_products ($products)  
{
    if (!empty($products)) // No point proceeding if there are no products
    {
        array_map('insert_product', $products); // Run 'insert_product' function from above for each product
    }
}

$json = file_get_contents('my-product-data.json'); // Get json from sample file
$products_data = json_decode($json, true); // Decode it into an array

insert_products($products_data);

my-product-data.json

[
    {
        "name"        : "T-Shirt",
        "sku"         : "TS1000",
        "description" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ac erat maximus augue accumsan egestas. Quisque posuere augue quis libero molestie posuere.",
        "categories"  : [
            "Clothes", "Mens"
        ],
        "available_attributes": [
            "size", "color"
        ],
        "variations":
        [
            {
                "attributes": {
                    "size"  : "Small",
                    "color" : "Red"
                },
                "price" : "8.00"
            },
            {
                "attributes": {
                    "size"  : "Medium",
                    "color" : "Red"
                },
                "price" : "10.00"
            },
            {
                "attributes": {
                    "size"  : "Small",
                    "color" : "Blue"
                },
                "price" : "8.00"
            },
            {
                "attributes": {
                    "size"  : "Large",
                    "color" : "Blue"
                },
                "price" : "12.00"
            }                           
        ]
    }
]

执行此代码后,将创建一个简单的产品。

3 个答案:

答案 0 :(得分:1)

这是使其成为可变产品的部分:

wp_set_object_terms($post_id, 'variable', 'product_type');

确保使用true作为第4个参数,以避免使用其他术语:

wp_set_object_terms($post_id, 'variable', 'product_type', true); 

如果您查看insert_product_attributes的代码,您会看到它实际上正在使用&#34;变量&#34;术语(我想2016年的行为不同)。

最后,清除该产品的瞬态可能是个好主意:

delete_transient( 'wc_product_children_' . $post_id );
delete_transient( 'wc_var_prices_' . $post_id );

我刚尝试过,它正确导入了我的变体。

答案 1 :(得分:0)

在我使用Woocommerce REST API之前,我一直在同一个博客上并感到沮丧。我认为没有其他方法可以创建具有变体的产品而无需通过API请遵循此link并避免挫败感,否则您将搜索整个网络并且找不到任何有用的东西,并且出于某种原因许多博主不会告诉你他们会一直告诉你,你和你的代码都是问题所在。

答案 2 :(得分:-1)

看看专业插件WP-ALL-IMPORT
它有一个woocommerce插件。
在这里查看他们的视频:http://www.wpallimport.com/woocommerce-product-import/
它将根据json文件中的变量创建具有属性的woocommerce变量产品
它会有你想要的一切:-)
非常好的拖放功能......为我节省了很多时间: - )