簡體   English   中英

在產品檔案中顯示特定父類別的子類別?

[英]Display the child category of a specific parent category inside a product archive?

我創建了一個名為“brands”的父類別 - 該類別的ID為“10”。

在里面我添加了像“耐克”,“阿迪達斯”等兒童類別。

在我的產品檔案中,我希望顯示僅與父類別“品牌”(ID 10)相關聯的子類別的名稱。

例如:如果產品與“Nike”(誰是“品牌”的孩子)相關聯 - 它將顯示“Nike”。如果不是 - 什么都不顯示。

我嘗試了流動但沒有為我工作:

<?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;
}
?>

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

為了實現這一目標,您需要使用: 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;
    }
}
 ?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM