Разрешить отложенные заказы и уведомить клиента о родительских категориях продуктов в Woocommerce

В woocommerce я использовал код, основанный на моем предыдущем потоке:
Разрешить отложенные заказы и уведомить клиентов о конкретных категориях продуктов в Woocommerce

add_filter( 'woocommerce_product_is_in_stock', 'filter_product_is_in_stock', 10, 2 );
function filter_product_is_in_stock( $is_in_stock, $product ){
    // Here set the products categories in the array (can be terms ids, slugs or names)
    $categories = array("clothing");

    if( has_term( $categories, 'product_cat', $product->get_id() ) ){
        $is_in_stock = true;
    }
    return $is_in_stock;
}

add_filter( 'woocommerce_product_backorders_allowed', 'filter_products_backorders_allowed', 10, 3 );
function filter_products_backorders_allowed( $backorder_allowed, $product_id, $product ){
    // Here set the products categories in the array (can be terms ids, slugs or names)
    $categories = array("clothing");

    if( has_term( $categories, 'product_cat', $product_id ) ){
        $backorder_allowed = true;
    }
    return $backorder_allowed;
}

add_filter( 'woocommerce_product_backorders_require_notification', 'filter_product_backorders_require_notification', 10, 2 );
function filter_product_backorders_require_notification( $notify, $product ){
    // Here set the products categories in the array (can be terms ids, slugs or names)
    $categories = array("clothing");

    if( has_term( $categories, 'product_cat', $product->get_id() ) ){
        $notify = true;
    }
    return $notify;
}

Но, когда я использовал корневые категории продуктов, похоже, что это не работает.

Как я могу получить корневые категории продуктов в операторах if кода?


person Erwin Manalang    schedule 29.09.2018    source источник


Ответы (1)


Обновление 2 - 17 ноября 2018 г. (исправлена ​​ошибка и немного исправлено)

Чтобы заставить его работать для родительских категорий, мы добавляем настраиваемую условную функцию, которая проверяет родительские категории продуктов (где вы определяете свои целевые родительские категории продуктов):

// Custom conditional function that checks for parent product categories
function has_parent_terms( $product_id ) {
    // HERE define the parent products categories SLUGS in the array
    $categories = array("clothing", "posters");

    $parent_term_ids = $categories_ids = array(); // Initializing

    // Convert categories term slugs to categories term ids
    foreach ( $categories as $category ){
        $categories_ids[] = get_term_by('slug', $category, 'product_cat')->term_id;
    }

    $terms = get_the_terms( $product_id, 'product_cat' );

    if( ! $terms ) return false; // Check that is not empty

    // Loop through the current product category terms to get only parent main category term
    foreach( $terms as $term ){
        if( $term->parent > 0 ){
            $parent_term_ids[] = $term->parent; // Set the parent product category
        } else {
            $parent_term_ids[] = $term->term_id; // It is the Main category term and we set it.
        }
    }
    return array_intersect( $categories_ids, $parent_term_ids ) ? true : false;
}

add_filter( 'woocommerce_product_is_in_stock', 'filter_product_is_in_stock', 10, 2 );
function filter_product_is_in_stock( $is_in_stock, $product ){
    // For product variations
    $product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();

    if( has_parent_terms( $product->get_id() ) ){
        $is_in_stock = true;
    }
    return $is_in_stock;
}

add_filter( 'woocommerce_product_backorders_allowed', 'filter_products_backorders_allowed', 10, 3 );
function filter_products_backorders_allowed( $backorder_allowed, $product_id, $product ){
    // For product variations
    $product_id = $product->is_type('variation') ? $product->get_parent_id() : $product_id;

    if( has_parent_terms( $product_id ) ){
        $backorder_allowed = true;
    }
    return $backorder_allowed;
}

add_filter( 'woocommerce_product_backorders_require_notification', 'filter_product_backorders_require_notification', 10, 2 );
function filter_product_backorders_require_notification( $notify, $product ){
    // For product variations
    $product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();

    if( has_parent_terms( $product->get_id() ) ){
        $notify = true;
    }
    return $notify;
}

Код находится в файле function.php вашей активной дочерней темы (или активной темы). Проверено и работает.

По теме: Разрешить отложенные заказы и уведомить клиент для определенных категорий продуктов в Woocommerce

person LoicTheAztec    schedule 29.09.2018
comment
как я могу добавить несколько категорий в массив, сэр? это работает отлично - person Erwin Manalang; 29.09.2018
comment
@ErwinManalang Просто добавьте столько, сколько хотите, в первый массив (первая функция), где вы определяете свои родительские категории SLUGS, например, $categories = array("clothing", "posters"); - person LoicTheAztec; 29.09.2018
comment
спасибо большое, решил мою проблему. Можно ли оставить массив категорий пустым? именно так? add_filter ('woocommerce_product_is_in_stock', 'filter_product_is_in_stock', 10, 2); function filter_product_is_in_stock ($ is_in_stock, $ product) {// Здесь устанавливаются категории товаров в массиве (могут быть идентификаторы терминов, ярлыки или названия) $ Categories = array (); если (has_parent_term ($ product- ›get_id ())) {$ is_in_stock = true; } return $ is_in_stock; } Я хочу изменить только родительскую категорию - person Erwin Manalang; 29.09.2018
comment
@ErwinManalang Если вы оставите поле пустым, код вам не понадобится, ничего не произойдет ... - person LoicTheAztec; 29.09.2018