Применить скрипт только к категориям первого и второго уровня WooCommerce - PullRequest
0 голосов
/ 17 июня 2020

Мне нужно добавить скрипт функциями php по разным спецификациям c категорий.

Пример 1 категории: Автомобиль -> Bmw -> x1. (Это только пример, у меня различные иерархии категорий, как это)

Мне нужно применить этот скрипт только к категории «автомобиль» и категории «bmw», поэтому только для категорий первого и второго уровня.

Как я могу это сделать?

1 Ответ

0 голосов
/ 17 июня 2020

Ниже вы найдете 3 условные функции, которые позволят вам проверить, является ли термин из:

  • Только категория продукта 1-го уровня
  • Только категория продукта 2-го уровня
  • Категория продукта 1-го или 2-го уровня

Все 3 условные функции работают с идентификатором термина категории продукта, slug или именем.

// Utility function:  Get the WP_Term object from term ID, slug or name
function wc_category_to_wp_term( $term, $taxonomy ) {
    if( is_numeric( $term ) && term_exists( $term, $taxonomy ) ) {
        return get_term( (int) $term, $taxonomy );
    } elseif ( is_string( $term ) && term_exists( $term, $taxonomy ) ) {
        return get_term_by( 'slug', sanitize_title( $term ), $taxonomy );
    } elseif ( is_a( $term, 'WP_Term' ) && term_exists( $term->slug, $taxonomy ) ) {
        return $term;
    }
    return false;
}

// Conditional function to check if  if a product category is a top level term
function is_wc_cat_lvl_1( $category, $taxonomy = 'product_cat' ) {
    if( $term = wc_category_to_wp_term( $category, $taxonomy ) ) {
        return ( $term->parent === 0 ) ? true : false;
    }
    return false;
}

// Conditional function to check if a product category is a second level term
function is_wc_cat_lvl_2( $category, $taxonomy = 'product_cat' ) {
    if( ( $term = wc_category_to_wp_term( $category, $taxonomy ) ) && $term->parent !== 0 ) {
        $ancestors = get_ancestors( $term->term_id, $taxonomy );

        // Loop through ancestors terms to get the 1st level term
        foreach( $ancestors as $parent_term_id ){
            // Get the 1st level category
            if ( get_term($parent_term_id, $taxonomy)->parent === 0 ) {
                $first_level_id = $parent_term_id;
                break; // stop the loop
            }
        }
        return isset($first_level_id) && $first_level_id === $term->parent ? true : false;
    }
    return false;
}

// Conditional function to check if a product category is a first or second level term
function is_wc_cat_lvl_1_or_2( $category, $taxonomy = 'product_cat' ) {
    $lvl_1 = is_wc_cat_lvl_1( $category, $taxonomy = 'product_cat' );
    $lvl_2 = is_wc_cat_lvl_2( $category, $taxonomy = 'product_cat' );

    return $lvl_1 || $lvl_2 ? true : false;
}

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


Пример использования - Отображение, если термин категории продукта относится к 1-му или 2-му уровню категории продукта:

$term1 = "Clothing"; // a 1st level category
$term2 = "Hoodies"; // a 2nd level category
$term3 = "Levis"; // a 3rd level category

echo  'Is "' . $term1 . '" a level 1 or 2 category: ' . ( is_wc_cat_lvl_1_or_2( $term1 ) ? 'YES' : 'NO' ) . '<br>'; 
echo  'Is "' . $term2 . '" a level 1 or 2 category: ' . ( is_wc_cat_lvl_1_or_2( $term2 ) ? 'YES' : 'NO' ) . '<br>';
echo  'Is "' . $term3 . '" a level 1 or 2 category: ' . ( is_wc_cat_lvl_1_or_2( $term3 ) ? 'YES' : 'NO' ) . '<br>'; 

Будет выведено:

Является ли «Одежда» категорией 1 или 2 уровня: ДА
Является ли «Толстовки» категорией 1 или 2 уровня: ДА
Является ли «Levis» категорией 1 или 2 уровня: НЕТ

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...