无法为以编程方式创建的 WooCommerce 产品选择变体

问题描述

我正在使用自定义 PHP 脚本来创建 WooCommerce 产品的变体。用户通过选择字段选择产品的“尺寸”和“颜色”,并在此基础上创建变体。

工作正常,产品是用正确的价格、属性和变化创建的。 除非您在尝试购物时无法选择实际变体(它们被“禁用”)。

当我进入 WooCommerce 的后端并在那里打开产品并点击产品上的蓝色“更新”按钮时,它会按预期工作,并且可以在前端选择和购买变体。

在创建变体后,是否有任何功能可以在 PHP 中“强制更新”产品?

After creating the product/variations programatically

--

After hitting Update-button back-end it works as intended

在将颜色和尺寸作为产品属性添加的代码下方。还创建一个以“任何颜色”和“任何尺寸”为规则的单一变体。

function save_wc_custom_attributes($post_id,$custom_attributes) {
$i = 0;
$product = wc_get_product( $post_id );
$product_id = $post_id;
$terms = wp_get_post_terms( $post_id,'pa_farge') ;
// Remove existing colors from the product
foreach ( $terms as $term ) {
  wp_remove_object_terms( $post_id,$term->term_id,'pa_farge' );
}
$terms = wp_get_post_terms( $post_id,'pa_str') ;
// Remove existing sizes from the product
foreach ( $terms as $term ) {
  wp_remove_object_terms( $post_id,'pa_str' );
}

foreach ($custom_attributes as $name => $value) {
    // Relate post to a custom attribute,add term if it does not exist
    wp_set_object_terms($post_id,$value,$name,true);
    // Create product attributes array
    $product_attributes[$i] = array(
        'name' => $name,// set attribute name
        'value' => $value,// set attribute value
        'is_visible' => 1,'is_variation' => 1,'is_taxonomy' => 1
    );
    $i++;
}
// Now update the post with its new attributes
update_post_meta($post_id,'_product_attributes',$product_attributes);
// Details for the variation
$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()
);

if( !$product->has_child() ) { 
  // Creating a single variation if none exists
  $variation_id = wp_insert_post( $variation_post );
  $variation = new WC_Product_Variation( $variation_id );
  $variation->set_regular_price( $product->get_price() );
  $variation->save(); // Save the data
  $product_variable = new WC_Product_Variable($post_id);
  $product_variable->sync($post_id);
  wc_delete_product_transients($post_id);
}
else {
  // Update the variation if it already exists
  $product_variable = new WC_Product_Variable($post_id);
  $product_variable->sync($post_id);
  wc_delete_product_transients($post_id);
}
$product->save();
}

解决方法

您的实际代码只是将产品属性设置为主要变量产品,但它没有为产品变体设置任何属性……所以问题可能与此变量产品有关……

所以尝试简单地在代码末尾添加:

$product = wc_get_product( $post_id );
$product->save();

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...