2016-05-21 89 views
1

我已經創建了一個名爲「品牌」的父類別 - 該類別的ID是「10」。它裏面我已經添加子類別,如「耐克」「阿迪達斯在產品檔案中顯示特定父類別的子類別?

」等

裏面我的產品檔案,我想只顯示與父類別相關聯的子類別 的名字「品牌」( ID 10)。

例如:如果一個產品有「耐克」(誰是「品牌」孩子相關的 - 它會顯示「耐克」如果不可─顯示什麼

我已經試過了流動的,但沒有任何事情工作對我來說:

<?php 
$categories = get_the_terms(get_the_ID(), '10'); 
if ($categories && ! is_wp_error($category)) : 
    foreach($categories as $category) : 
     $children = get_categories(array ('taxonomy' => '10', 'parent' => $category->term_id)); 

     if (count($children) == 0) { 
      echo $category->name; 
     } 
    endforeach; 
endif; 
?> 

和:

<?php 
$categories = get_the_terms(get_the_ID(), '10'); 
if ($categories && ! is_wp_error($category)) : 
    foreach($categories as $category) : 
     $children = get_categories(array ('taxonomy' => '10', 'parent' => $category->term_id)); 
     if (count($children) == 0) { ?> 
     <span class="product-sub-cats"><?php echo $category->name; ?></span> 
     <?php } 
    endforeach; 
endif; ?> 

而且也:

<?php 
if($termid->parent > 10) { 
    $args = array(
     'orderby'  => 'name', 
     'order'   => 'ASC', 
     'hide_empty' => false, 
     'child_of'  => $termid->parent, 
    ); 

$categories = get_the_terms(get_the_ID(), 'product_cat', $args); 
if ($categories && ! is_wp_error($category)) : 
    foreach($categories as $category) : 
     $children = get_categories(array ('taxonomy' => 'product_cat', 'parent' => $category->term_id)); 
     if (count($children) == 0) { ?> 
     <span class="product-sub-cats"><?php echo $category->name; ?></span> 
     <?php } 
    endforeach; 
endif; 
} 
?> 

回答

0

我找到了解決這個問題的辦法。

爲了實現這一點,你需要使用: https://codex.wordpress.org/Function_Reference/wp_get_post_terms

這是爲我工作的代碼:

<?php 
global $post; 
$brands_id = get_term_by('slug', 'PARENT-CAT-SLUG', 'product_cat'); 

$terms = get_the_terms($post->ID, 'product_cat'); 
foreach ($terms as $term) { 
    if($term->parent === $brands_id->term_id) { ?> 
     <span class="product-sub-cats"><?php echo $term->name; ?></span> 
     <?php break; 
    } 
} 
?> 
相關問題