WooCommerce Auto Assign Product Category с использованием If Else Statement - PullRequest
0 голосов
/ 06 декабря 2018

Для гуру woocommerce у меня есть 4 категории продуктов, называемые A, B, C, D, с соответствующим идентификатором категории 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, категория A и все другие категории будут сняты, кроме категории B.

Любая идея, что не так

1 Ответ

0 голосов
/ 06 декабря 2018

Попробуйте это:

$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');
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...