我知道这里曾经回答过类似的问题,但我尝试了一下,但仍然无法弄清楚我遇到的这个问题。
因此,我尝试使用自己创建的插件在WooCommerce中添加产品属性,例如,当管理员创建具有属性size
的新产品时,需要另一个名为color
的属性自动创建,并且每个size
都需要一个color
。
function add_product_variations( $meta_id, $post_id, $meta_key, $meta_value ) {
global $wpdb;
if ( get_post_type( $post_id ) == 'product' ) {
$product = wc_get_product( $post_id );
$availableColors = ['red', 'blue', 'green'];
$product_attributes = array();
$product_attributes['colors'] = array(
'name' => 'Colors',
'value' => implode('|', $availableColors),
'position' => 0,
'is_visible' => 1,
'is_variation' => 1,
'is_taxonomy' => 0
);
update_post_meta($product->id, '_product_attributes', $product_attributes);
wp_add_object_terms($product->id, implode('|', $availableColors), 'colors', true);
foreach ($availableColors as $color) {
$colorClean = preg_replace("/[^0-9a-zA-Z_-] +/", "", $color);
$post_name = 'product-' . $product->id . '-color-' . $colorClean;
$my_post = array(
'post_title' => 'color ' . $color . ' for #' . $product->id,
'post_name' => $post_name,
'post_status' => 'publish',
'post_parent' => $product->id,
'post_type' => 'product_variation',
'guid' => home_url() . '/?product_variation=' . $post_name
);
$attID = $wpdb->get_var("SELECT count(post_title) FROM $wpdb->posts WHERE post_name like '$post_name'");
if ($attID < 1) {
$attID = wp_insert_post($my_post);
}
update_post_meta($attID, 'attribute_dates', $color);
update_post_meta($attID, '_regular_price', 100);
update_post_meta($attID, '_sku', $post_name);
update_post_meta($attID, '_virtual', 'no');
update_post_meta($attID, '_downloadable', 'no');
update_post_meta($attID, '_manage_stock', 'no');
update_post_meta($attID, '_stock_status', 'instock');
}
}
}
add_action( 'added_post_meta', 'add_product_variations', 10, 4 );
这是我已经在运行的代码。当我不手动创建产品属性时,此代码可以正常工作,因此只能创建一个名为color的产品属性,并带有选项“ red”,“ blue”和“ green”
但是问题出在我手动添加产品属性,然后代码不再创建color
属性。
感谢您的帮助。