【问题标题】:WP Get IDs of parent categories onlyWP 仅获取父类别的 ID
【发布时间】:2020-08-05 19:23:40
【问题描述】:

下面的 sn-p 工作正常,但我已经硬编码了父类别 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>

【问题讨论】:

    标签: php wordpress categories


    【解决方案1】:

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

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

    【讨论】:

    • 它打印页面上的所有类别。我已经替换了你的代码块,但它不起作用。
    • 您的类别设置如何?原始帖子似乎暗示您硬编码的两个 ID 是唯一的父母?不是这样吗?如果是这样 - 以上应该可以工作。
    • 当我 print_r($cat);它以正确的方式向我展示了两个父类别。但是当我替换你提供的 sn-p 然后 print_r($cat);它显示了太多的 WP_Term 对象。
    • 返回的其他 WP_Term 对象是什么?交叉引用这些会很有用。我不确定您要在这里提取什么分类法-可能是您希望这仅返回特定分类法的术语,但是您得到了其他分类法?参数数组也接受分类。我建议您在答案中查看上面的链接。
    • 谢谢让我看一下,我认为你是对的,听起来我只想获取层次结构顶层的所有类别。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-12-06
      • 2020-03-05
      • 2017-09-24
      • 2012-06-03
      • 1970-01-01
      • 1970-01-01
      • 2017-12-21
      • 2013-05-21
      • 1970-01-01
      相关资源
      最近更新 更多