【问题标题】:WooCommerce Auto Assign Product Category using If Else StatementWooCommerce 使用 If Else 语句自动分配产品类别
【发布时间】:2018-12-06 21:58:58
【问题描述】:

对于 woocommerce 大师,我有 4 个产品类别,分别称为 A、B、C、D,类别 ID 分别为 1、2、3、4。

我想要达到的目标:

  1. 如果产品类别 A 被勾选,类别 B 将自动不勾选,不会影响其他类别。
  2. 如果产品类别 A 未勾选,则类别 B 将自动勾选,不会影响其他类别。

根据Automatically assign products to a defined product category in 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,则类别 A 和除类别 B 之外的所有其他类别都将取消选中。

知道哪里错了吗?

【问题讨论】:

    标签: php wordpress woocommerce taxonomy-terms


    【解决方案1】:

    试试这个:

    $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');
    

    【讨论】:

    • 谢谢你的作品!不过有一个问题,如果我想添加“如果选中 A 类,请将产品状态设置为缺货”怎么办?
    • 你想为此创建一个新问题>
    • orite,我稍后会创建它。
    猜你喜欢
    • 2018-11-30
    • 1970-01-01
    • 2018-05-18
    • 2018-06-26
    • 2018-03-26
    • 1970-01-01
    • 2016-09-04
    • 2016-03-20
    • 1970-01-01
    相关资源
    最近更新 更多