繁体   English   中英

WooCommerce使用If Else语句自动分配产品类别

[英]WooCommerce Auto Assign Product Category using If Else Statement

对于woocommerce专家,我有4个产品类别,分别为A,B,C,D,类别ID为1,2,3,4。

我想要达到的目标:

  1. 如果选中了产品类别A,则不会自动检查类别B,而不会影响其他类别。
  2. 如果未选中产品类别A,则将自动检查类别B,而不会影响其他类别。

基于这篇文章, 在WooCommerce中将产品自动分配给定义的产品类别 ,我编写了这些代码。

// Only on WooCommerce Product edit pages (Admin)
add_action( 'save_post', 'auto_add_product_category', 50, 3 );
function auto_add_product_category( $post_id, $post, $update ) {

if ( $post->post_type != 'product') return; // Only products

// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
    return $post_id;

// Check the user's permissions.
if ( ! current_user_can( 'edit_product', $post_id ) )
    return $post_id;

$term_id = 2; // <== Your targeted product category term ID
$term_id2 = 1; // <== Your targeted product category term ID
$taxonomy = 'product_cat'; // The taxonomy for Product category

// If the product has not "93" category id and if "93" category exist
if ( ! has_term( $term_id2, 'product_cat', $post_id ) && term_exists( $term_id2, $taxonomy ) )
    wp_set_post_terms( $post_id, $term_id, $taxonomy, true ); // we set this product category
else
    wp_set_post_terms( $post_id, $term_id, $taxonomy, false );
}

2号工作正常,但对于1号,则会发生以下情况:

  1. 如果选中了产品类别A,则类别B和所有其他类别都将取消选中,类别B除外。

知道有什么问题吗?

尝试这个:

$term_id_A = 1,
$term_id_B = 2;
//get all the terms:
$terms = get_the_terms( $post_id, 'product_cat' );
//just their IDs:
$term_ids = wp_list_pluck( $terms, 'term_id' );

if(in_array($term_id_A, $term_ids) && ($key = array_search($term_id_B, $term_ids)) !== false) {
    unset($term_ids[$key]);
} elseif(!in_array($term_id_A, $term_ids) && !in_array($term_id_B, $term_ids)) {
    $term_ids[] = $term_id_B;
}
wp_set_post_terms($post_id, $term_ids, 'product_cat');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM