WP 仅获取父类别的 ID

WP Get IDs of parent categories only

下面的代码片段工作正常,但我已经硬编码了父类别 ID,现在我正在寻找一种方法来摆脱硬编码 ID。

      <div class="row">
                    <?php
                     $catsArray = array(176, 175); // This line need to be dynamic and the IDs are parent categories.
                      $categories = get_terms(
                              array(
                          'hide_empty' => false,
                          'include' => $catsArray, 'orderby'  => 'include'

                      ) );

                      foreach ($categories as $key => $cat) {
        
                      $cat_thumb_id = get_term_meta( $cat->term_id, 'thumbnail_id', true );



                      $term_link = get_category_link( $cat->term_id );
                     ?>
                    <div class="col-md-6">
                      <div class="sellers-wrap is-revealing">
                        <figure>
                          <img src="<?php echo $cat_img; ?>" alt="" class="img-fluid">
                        </figure>
                        <div class="sellers-text">
                            <p><strong><?php echo $cat->name; ?></strong></p>
                          
                        </div>
                      </div>
                    </div>
                 <?php } ?>
                  </div>

您必须 get_terms 的第一个参数是参数数组。所有可能的值都记录在此处:https://developer.wordpress.org/reference/classes/wp_term_query/__construct/。听起来您只想获取层次结构顶层的所有类别(即没有父级)。所以要做到这一点,你可以只使用 'parent' 参数并传递 0。像这样:

$categories = get_terms([
    'hide_empty'    => false,
    'parent'        => 0
]);

如果传递 0,则只返回顶级术语。

$categories = get_terms( 
 'category', 
 array('parent' => 0)
);