Показать самую глубокую дочернюю категорию для текущего продукта в woocommerce

Кажется, что это должно быть легко сделать, но я не смог, и не могу найти никаких сообщений по этому поводу.

Я могу отобразить все категории, связанные с продуктом, или верхнюю категорию, но как отобразить только самую низкую / самую глубокую категорию для продукта?

Cat-A [x]
Cat-B [x]
Cat-C [x]
Cat-D [ ]
Cat-E [ ]
Cat-F [ ]
Cat-G [ ]
Cat-H [ ]

Если этот пример является происхождением продукта, все, что я хочу напечатать, это «Cat-C».

Но я не хочу вручную устанавливать уровень категории, как другие решения, я хочу, чтобы он всегда печатал самый младший дочерний элемент, будь то продукт на странице архива или страница отдельного продукта.

Есть идеи, как это можно / нужно сделать?

2

Решение

Попробуйте что-то вроде:

// get all product cats for the current post
$categories = get_the_terms( get_the_ID(), 'product_cat' );

// wrapper to hide any errors from top level categories or products without category
if ( $categories && ! is_wp_error( $category ) ) :

// loop through each cat
foreach($categories as $category) :
// get the children (if any) of the current cat
$children = get_categories( array ('taxonomy' => 'product_cat', 'parent' => $category->term_id ));

if ( count($children) == 0 ) {
// if no children, then echo the category name.
echo $category->name;
}
endforeach;

endif;
5

Другие решения

Я наконец нашел ответ на https://wordpress.stackexchange.com/a/55921/59863 Я добавил правильную таксономию для woocommerce, а внизу — foreach / echo, чтобы выложить название.

//Get all terms associated with post in woocommerce's taxonomy 'product_cat'
$terms = get_the_terms( $post->ID, 'product_cat' );

//Get an array of their IDs
$term_ids = wp_list_pluck($terms,'term_id');

//Get array of parents - 0 is not a parent
$parents = array_filter(wp_list_pluck($terms,'parent'));

//Get array of IDs of terms which are not parents.
$term_ids_not_parents = array_diff($term_ids,  $parents);

//Get corresponding term objects.
$terms_not_parents = array_intersect_key($terms,  $term_ids_not_parents);

//Extract the name of the category from the array and post it.
foreach($terms_not_parents as $term_not_parent)
echo $term_not_parent->name;

Единственным недостатком этого кода является то, что если у продукта есть только 1 категория с родительским значением 0, он сломается. В данный момент мне не нужна эта функциональность, но я собираюсь вернуться и исправить это с помощью «если ноль делать это вместо этого».

0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector