通过PHP创建WooCommerce变量订阅产品和变体无法在变体上设置属性名称和值

时间:2020-11-05 02:31:16

标签: wordpress woocommerce variable-subscription

对很长的“标题”表示歉意,但我试图具体说明自己遇到的问题。

我正在研究一些PHP代码,这些代码在WordPress安装中循环遍历自定义帖子类型,然后针对该帖子类型中的每个帖子,在WooCommerce中创建一个变量订阅产品,并在该产品上生成许多变体。 / p>

为了创建我的代码,我引用了以下问题,并将“ create_product_variation”功能用作我的代码的一部分:Create programmatically a WooCommerce product variation with new attribute values

我可以正常工作-它遍历帖子,为每个帖子创建变量订阅产品,然后为每个产品生成产品变体。

但是,我的代码无法为变体中使用的属性设置变体名称/值。这是屏幕截图:

Text

我整天都在努力编写代码来解决问题,但是我觉得自己碰壁了,因此我希望对社区有所了解。

这是我的代码:

// Loop through RSS Feeds //

$rss_feeds = new WP_Query(
    array(
        'post_type' => 'wprss_feed',
        'posts_per_page' => -1 // unlimited
    )
);
while($rss_feeds->have_posts()) : $rss_feeds->the_post();

    // Get Feed Title and Slug

    $rss_feed_title = get_the_title();
    $rss_feed_slug = $post->post_name;

    // Create an array for basic WooCommerce Item data.

    $woocommerce_item = array(
        'Name' => $rss_feed_title,
        'Description' => '',
        'SKU' => $rss_feed_slug
    );

    // Add check to see if a product with this name or slug already exists, prevent duplicate products from being created

    $found_product_title = get_page_by_title($rss_feed_title, OBJECT, 'product');
    $found_product_id = $found_product_title->ID;

    if($found_product_id == ''){
        
        // Create product, as it does not exist
        
        // Insert the basic product data

        $product_id = wp_insert_post(array(
            'post_author' => 1, // admin
            'post_title' => $woocommerce_item['Name'],
            'post_content' => $woocommerce_item['Description'],
            'post_status' => 'publish',
            'post_type' => 'product',
        ));

        // Set Product Type to Variable Subscription

        wp_set_object_terms($product_id, 'variable-subscription', 'product_type');
        
        // Set Attributes
        
        $my_product_attributes = array(
            'Amount' => '$5 | $10 | $20',
            'Frequency' => 'Monthly | One-time'
        );
        wc_product_set_attributes($product_id, $my_product_attributes);
        
        // Generate Product Variations
        
        $parent_id = $product_id; // Or get the variable product id dynamically

        // Variation data
        
        $variation_one = array(
            'attributes' => array(
                'amount'  => '$5',
                'frequency' => 'Monthly',
            ),
            'sku'           => 'TEST123',
            'regular_price' => '5.00',
            'sale_price'    => '',
            'stock_qty'     => '',
            'manage_stock'  => 'no',
            'subscription_period_interval' => 1, // 1 = every , 2 = every 2nd, 3 = every 3rd, etc
            'subscription_period' => 'month', // day, week, month, year
            'subscription_length' => 1, // 0 = never expire, 1 = 1 period, 2 = 2 period, etc
            'subscription_sign_up_fee' => 0,
            'subscription_trial_period' => 'day', // day, week, month, year
            'subscription_trial_length' => 5,
            'subscription_payment_sync_date' => 0,
        );
        
        create_product_variation($parent_id, $variation_one);

        echo 'Product ID #'.$product_id.' was created.<br/>';
        
    } else {
        
        // Do nothing, as the product already exists
        
        echo 'A product already exists with the "'.$rss_feed_title.'" name. Skipped product creation.</br>';
        
    }

endwhile;
wp_reset_postdata();

以下是该函数,与上面的问题参考相比,该函数进行了一些修改:

function create_product_variation( $product_id, $variation_data ){
    // Get the Variable product object (parent)
    $product = wc_get_product($product_id);

    $variation_post = array(
        'post_title'  => $product->get_name(),
        'post_name'   => 'product-'.$product_id.'-variation',
        'post_status' => 'publish',
        'post_parent' => $product_id,
        'post_type'   => 'product_variation',
        'guid'        => $product->get_permalink()
    );

    // Creating the product variation
    $variation_id = wp_insert_post( $variation_post );

    // Get an instance of the WC_Product_Variation object
    $variation = new WC_Product_Variation( $variation_id );

    // Iterating through the variations attributes
    foreach ($variation_data['attributes'] as $attribute => $term_name )
    {
        $taxonomy = 'pa_'.$attribute; // The attribute taxonomy

        // If taxonomy doesn't exists we create it (Thanks to Carl F. Corneil)
        if( ! taxonomy_exists( $taxonomy ) ){
            register_taxonomy(
                $taxonomy,
               'product_variation',
                array(
                    'hierarchical' => false,
                    'label' => ucfirst( $attribute ),
                    'query_var' => true,
                    'rewrite' => array( 'slug' => sanitize_title($attribute) ), // The base slug
                ),
            );
        }

        // Check if the Term name exist and if not we create it.
        if( ! term_exists( $term_name, $taxonomy ) )
            wp_insert_term( $term_name, $taxonomy ); // Create the term

        $term_slug = get_term_by('name', $term_name, $taxonomy )->slug; // Get the term slug

        // Get the post Terms names from the parent variable product.
        $post_term_names =  wp_get_post_terms( $product_id, $taxonomy, array('fields' => 'names') );

        // Check if the post term exist and if not we set it in the parent variable product.
        if( ! in_array( $term_name, $post_term_names ) )
            wp_set_post_terms( $product_id, $term_name, $taxonomy, true );

        // Set/save the attribute data in the product variation
        update_post_meta( $variation_id, 'attribute_'.$taxonomy, $term_slug );
        
    }

    ## Set/save all other data

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

    // Prices
    if( empty( $variation_data['sale_price'] ) ){
        $variation->set_price( $variation_data['regular_price'] );
    } else {
        $variation->set_price( $variation_data['sale_price'] );
        $variation->set_sale_price( $variation_data['sale_price'] );
    }
    $variation->set_regular_price( $variation_data['regular_price'] );

    // Stock
    if( ! empty($variation_data['stock_qty']) ){
        $variation->set_stock_quantity( $variation_data['stock_qty'] );
        $variation->set_manage_stock(true);
        $variation->set_stock_status('');
    } else {
        $variation->set_manage_stock(false);
    }
    
    $variation->set_weight(''); // weight (reseting)

    $variation->save(); // Save the data
    
    // Set other post meta - has to be done after variation save or it does not save the meta. I think the meta is created by default during the save function, so therefore we have to update post meta after the save.

    update_post_meta($variation_id, '_subscription_price', $variation_data['regular_price']);
    update_post_meta($variation_id, '_subscription_period', $variation_data['subscription_period']);
    update_post_meta($variation_id, '_subscription_period_interval', $variation_data['subscription_period_interval']); 
    update_post_meta($variation_id, '_subscription_length', $variation_data['subscription_length']); 
    update_post_meta($variation_id, '_subscription_sign_up_fee', $variation_data['subscription_sign_up_fee']);
    update_post_meta($variation_id, '_subscription_trial_period', $variation_data['subscription_trial_period']);
    update_post_meta($variation_id, '_subscription_trial_length', $variation_data['subscription_trial_length']); 
    update_post_meta($variation_id, '_subscription_payment_sync_date', $variation_data['subscription_payment_sync_date']);
    update_post_meta($variation_id, '_manage_stock', $variation_data['manage_stock']);
    update_post_meta($variation_id, '_min_price_variation_id', $variation_id);
    update_post_meta($variation_id, '_max_price_variation_id', $variation_id);
    update_post_meta($variation_id, '_min_variation_price', $variation_data['regular_price']);
    update_post_meta($variation_id, '_max_variation_price', $variation_data['regular_price']);
    update_post_meta($variation_id, '_min_variation_regular_price', $variation_data['regular_price']);
    update_post_meta($variation_id, '_max_variation_regular_price', $variation_data['regular_price']);
    
}

我认为问题可能出在设置属性的代码上,但是我不确定。

我希望在这里有所了解,以便可以正确设置“数量”和“频率”。

如果有关系,我已经在“产品”>“属性”下创建了属性。

生成的属性分类法是:

taxonomy = pa_amount

taxonomy = pa_frequency

不确定这是否完全相关,但是我现在对此有洞察力,并且在这个问题上全力以赴。我将不胜感激!

0 个答案:

没有答案