php物品类别选择添加,php-在Woocommerce上的产品中设置产品类别术语

更新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文件中.它应该工作.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值