【发布时间】:2021-01-19 14:23:39
【问题描述】:
我正在使用自定义 PHP 脚本来创建 WooCommerce 产品的变体。用户通过选择字段选择产品的“尺寸”和“颜色”,并在此基础上创建变体。
工作正常,以正确的价格、属性和变化创建产品。 除非您在尝试购物时无法选择实际的变体(它们被“禁用”)。
当我在 WooCommerce 中打开后端并在那里打开产品并点击产品上的蓝色“更新”按钮时,它会按预期工作,并且可以在前端选择和购买变体。
在创建变体后,是否有任何功能可以在 PHP 中“强制更新”产品?
--
在添加颜色和尺寸作为产品属性的代码下方。还创建一个以“任何颜色”和“任何尺寸”为规则的单一变体。
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, $term->term_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();
}
【问题讨论】:
标签: php wordpress woocommerce product custom-attributes