更新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();
}
下面是一个挂钩函数的示例,该函数将在产品编辑时自动设置产品类别术语.
Note: the product category terms need to exist in 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文件中.它应该工作.