在Woocommerce中,我有一个名为“平台”的产品属性,该属性的值为“蒸汽”:
所以我要批量导入产品,并且属性已经存在。
但是现在我必须为每个产品手动设置类别。 是否可以在功能中将“值”自动设置为“产品类别”?
此函数返回的属性值正确吗?
function get_attribute_value_from_name( $name ){
global $wpdb;
$name = 'Platform';
$attribute_value = $wpdb->get_var("SELECT attribute_value
FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
WHERE attribute_name LIKE '$name'");
return $attribute_value;
}
现在如何设置产品类别的值?
编辑:
$product = wc_get_product($id); //LOAD PRODUCT
global $product_attribute; //VARIABLE
$product_attribute = $product->get_attribute( 'Platform' ); //GET ATTRIBUTE OF PLATFORM
wp_set_object_terms( $post_id, $product_attribute, 'product_cat' ); //WRITE IT AS CATEGORY
$product->save(); //SAVE PRODUCT
这有意义吗?
答案 0 :(得分:3)
更新2 -设置产品中的现有产品类别术语(使用已定义的产品ID):
// Get an instance of the WC_Product object
$product = wc_get_product( $product_id );
$term_names = $product->get_attribute( 'Platform' ); // Can have many term names (coma separated)
$term_names = explode( ',', $term_names);
$term_ids = [];
// Loop through the terms
foreach( $term_names as $term_name ) {
// Get the term ID and check if it exist
if( $term_id = term_exists( $term_name, 'product_cat' ) ) {
// Add each term ID in an array
$term_ids[] = $term_id;
}
}
// Append the product category terms in the product
if( sizeof($term_ids) > 0 ) {
$product->set_category_ids( $term_ids );
$product->save();
}
以下是挂钩函数的示例,该函数将在产品编辑时自动设置产品类别术语。
注意:woocommerce中必须存在产品类别术语
// Backend product creation
add_action( 'woocommerce_admin_process_product_object', 'add_product_category_terms_to_product', 100, 1 );
function add_product_category_terms_to_product( $product ){
global $pagenow;
// Only on product Edit
if( $pagenow != 'post.php' ) return; // Exit
if( $term_names = $product->get_attribute( 'Platform' ) )
$term_names = explode( ',', $term_names);
else
return; // Exit
$term_ids = [];
// Loop through the terms
foreach( $term_names as $term_name ) {
// Get the term ID and check if it exist
if( $term_id = term_exists( $term_name, 'product_cat' ) ) {
// Add each term ID in an array
$term_ids[] = $term_id;
}
}
// replace the product categories terms in the product
if( sizeof($term_ids) > 0 ) {
$product->set_category_ids( $term_ids );
}
// save is not needed in the function as this hook does that
}
代码进入您的活动子主题(或活动主题)的function.php文件中。应该可以。