php 在WooCommerce中以编程方式创建一个可变产品和两个新属性

368yc8dk  于 2022-12-28  发布在  PHP
关注(0)|答案(3)|浏览(138)

我想通过编程创建一个变量产品("父"产品),它有两个新的变量属性--所有这些都来自一个WordPress插件(所以没有对API的HTTP请求)。
这两个变量属性也应该动态创建。
如何才能做到这一点?
(with WooCommerce版本3)
更新:我已经写了更多的代码行在这方面,我希望,并尝试了许多事情来解决它,使用wooCommerce对象,并添加了失踪的数据,关于术语,termmeta,从术语与帖子的关系,在数据库中使用WordPress数据库对象-但没有什么足以使它工作。我不能针点我哪里出错-这就是为什么我不能提供一个狭窄的问题- stackoverflow更适合的东西。

ki1q1bka

ki1q1bka1#

    • 之后:**使用新属性值以编程方式创建WooCommerce产品变体

在这里,您可以使用新的产品属性+值创建新的可变产品:

/**
 * Save a new product attribute from his name (slug).
 *
 * @since 3.0.0
 * @param string $name  | The product attribute name (slug).
 * @param string $label | The product attribute label (name).
 */
function save_product_attribute_from_name( $name, $label='', $set=true ){
    if( ! function_exists ('get_attribute_id_from_name') ) return;

    global $wpdb;

    $label = $label == '' ? ucfirst($name) : $label;
    $attribute_id = get_attribute_id_from_name( $name );

    if( empty($attribute_id) ){
        $attribute_id = NULL;
    } else {
        $set = false;
    }
    $args = array(
        'attribute_id'      => $attribute_id,
        'attribute_name'    => $name,
        'attribute_label'   => $label,
        'attribute_type'    => 'select',
        'attribute_orderby' => 'menu_order',
        'attribute_public'  => 0,
    );

    if( empty($attribute_id) ) {
        $wpdb->insert(  "{$wpdb->prefix}woocommerce_attribute_taxonomies", $args );
        set_transient( 'wc_attribute_taxonomies', false );
    }

    if( $set ){
        $attributes = wc_get_attribute_taxonomies();
        $args['attribute_id'] = get_attribute_id_from_name( $name );
        $attributes[] = (object) $args;
        //print_r($attributes);
        set_transient( 'wc_attribute_taxonomies', $attributes );
    } else {
        return;
    }
}

/**
 * Get the product attribute ID from the name.
 *
 * @since 3.0.0
 * @param string $name | The name (slug).
 */
function get_attribute_id_from_name( $name ){
    global $wpdb;
    $attribute_id = $wpdb->get_col("SELECT attribute_id
    FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
    WHERE attribute_name LIKE '$name'");
    return reset($attribute_id);
}

/**
 * Create a new variable product (with new attributes if they are).
 * (Needed functions:
 *
 * @since 3.0.0
 * @param array $data | The data to insert in the product.
 */

function create_product_variation( $data ){
    if( ! function_exists ('save_product_attribute_from_name') ) return;

    $postname = sanitize_title( $data['title'] );
    $author = empty( $data['author'] ) ? '1' : $data['author'];

    $post_data = array(
        'post_author'   => $author,
        'post_name'     => $postname,
        'post_title'    => $data['title'],
        'post_content'  => $data['content'],
        'post_excerpt'  => $data['excerpt'],
        'post_status'   => 'publish',
        'ping_status'   => 'closed',
        'post_type'     => 'product',
        'guid'          => home_url( '/product/'.$postname.'/' ),
    );

    // Creating the product (post data)
    $product_id = wp_insert_post( $post_data );

    // Get an instance of the WC_Product_Variable object and save it
    $product = new WC_Product_Variable( $product_id );
    $product->save();

    ## ---------------------- Other optional data  ---------------------- ##
    ##     (see WC_Product and WC_Product_Variable setters methods)

    // THE PRICES (No prices yet as we need to create product variations)

    // IMAGES GALLERY
    if( ! empty( $data['gallery_ids'] ) && count( $data['gallery_ids'] ) > 0 )
        $product->set_gallery_image_ids( $data['gallery_ids'] );

    // SKU
    if( ! empty( $data['sku'] ) )
        $product->set_sku( $data['sku'] );

    // STOCK (stock will be managed in variations)
    $product->set_stock_quantity( $data['stock'] ); // Set a minimal stock quantity
    $product->set_manage_stock(true);
    $product->set_stock_status('');

    // Tax class
    if( empty( $data['tax_class'] ) )
        $product->set_tax_class( $data['tax_class'] );

    // WEIGHT
    if( ! empty($data['weight']) )
        $product->set_weight(''); // weight (reseting)
    else
        $product->set_weight($data['weight']);

    $product->validate_props(); // Check validation

    ## ---------------------- VARIATION ATTRIBUTES ---------------------- ##

    $product_attributes = array();

    foreach( $data['attributes'] as $key => $terms ){
        $taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
        $attr_label = ucfirst($key); // attribute label name
        $attr_name = ( wc_sanitize_taxonomy_name($key)); // attribute slug

        // NEW Attributes: Register and save them
        if( ! taxonomy_exists( $taxonomy ) )
            save_product_attribute_from_name( $attr_name, $attr_label );

        $product_attributes[$taxonomy] = array (
            'name'         => $taxonomy,
            'value'        => '',
            'position'     => '',
            'is_visible'   => 0,
            'is_variation' => 1,
            'is_taxonomy'  => 1
        );

        foreach( $terms as $value ){
            $term_name = ucfirst($value);
            $term_slug = sanitize_title($value);

            // Check if the Term name exist and if not we create it.
            if( ! term_exists( $value, $taxonomy ) )
                wp_insert_term( $term_name, $taxonomy, array('slug' => $term_slug ) ); // Create the term

            // Set attribute values
            wp_set_post_terms( $product_id, $term_name, $taxonomy, true );
        }
    }
    update_post_meta( $product_id, '_product_attributes', $product_attributes );
    $product->save(); // Save the data
}
  • 代码进入您的活动子主题(或活动主题)的function.php文件。* 测试和作品。
    • 用法**(示例包含2个新属性+值):
create_product_variation( array(
    'author'        => '', // optional
    'title'         => 'Woo special one',
    'content'       => '<p>This is the product content <br>A very nice product, soft and clear…<p>',
    'excerpt'       => 'The product short description…',
    'regular_price' => '16', // product regular price
    'sale_price'    => '', // product sale price (optional)
    'stock'         => '10', // Set a minimal stock quantity
    'image_id'      => '', // optional
    'gallery_ids'   => array(), // optional
    'sku'           => '', // optional
    'tax_class'     => '', // optional
    'weight'        => '', // optional
    // For NEW attributes/values use NAMES (not slugs)
    'attributes'    => array(
        'Attribute 1'   =>  array( 'Value 1', 'Value 2' ),
        'Attribute 2'   =>  array( 'Value 1', 'Value 2', 'Value 3' ),
    ),
) );

测试和工程。
相关:

  • 在Woocommerce中编程创建新的产品属性
  • 使用新属性值以编程方式创建WooCommerce产品变体
  • 在Woocommerce 3中使用CRUD方法以编程方式创建产品
kxkpmulp

kxkpmulp2#

您也可以使用新的原生函数从postmeta设置/获取数据。
这里是一个工作的例子(基于Woocommerce 3的默认虚拟产品)

//Create main product
$product = new WC_Product_Variable();

//Create the attribute object
$attribute = new WC_Product_Attribute();
//pa_size tax id
$attribute->set_id( 1 );
//pa_size slug
$attribute->set_name( 'pa_size' );

//Set terms slugs
$attribute->set_options( array(
        'blue',
        'grey'
) );
$attribute->set_position( 0 );

//If enabled
$attribute->set_visible( 1 );

//If we are going to use attribute in order to generate variations
$attribute->set_variation( 1 );

$product->set_attributes(array($attribute));

//Save main product to get its id
$id = $product->save();

$variation = new WC_Product_Variation();
$variation->set_regular_price(5);
$variation->set_parent_id($id);

//Set attributes requires a key/value containing
// tax and term slug
$variation->set_attributes(array(
        'pa_size' => 'blue'
));

//Save variation, returns variation id
$variation->save();

您可以使用Woocommerce 3和set_price,set_sku等提供的原生函数添加重量,税,SKU等。
将它 Package 在函数中,就可以开始了。

dsekswqp

dsekswqp3#

Sarakinos的答案只有两个小而重要的修改。
1.需要将$attribute->set_id()设置为0

  1. $attribute->set_name();$variation->set_attributes()不需要pa_前缀。方法已经处理了前缀。
    所以一个有效的代码应该是:
//Create main product
$product = new WC_Product_Variable();

//Create the attribute object
$attribute = new WC_Product_Attribute();

//pa_size tax id
$attribute->set_id( 0 ); // -> SET to 0

//pa_size slug
$attribute->set_name( 'size' ); // -> removed 'pa_' prefix

//Set terms slugs
$attribute->set_options( array(
    'blue',
    'grey'
) );

$attribute->set_position( 0 );

//If enabled
$attribute->set_visible( 1 );

//If we are going to use attribute in order to generate variations
$attribute->set_variation( 1 );

$product->set_attributes(array($attribute));

//Save main product to get its id
$id = $product->save();

$variation = new WC_Product_Variation();
$variation->set_regular_price(10);
$variation->set_parent_id($id);

//Set attributes requires a key/value containing
// tax and term slug
$variation->set_attributes(array(
    'size' => 'blue' // -> removed 'pa_' prefix
));

//Save variation, returns variation id
echo get_permalink ( $variation->save() );

// echo get_permalink( $id ); // -> returns a link to check the newly created product

请记住,产品将是最基本的,并且将命名为“product”。在使用$id = $product->save();保存它之前,您需要在$product中设置这些值。

相关问题