WP仅获取父类别的ID



下面的代码段运行良好,但我已经对父类别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>

必须获取的第一个参数是一个参数数组。此处记录了所有可能的值: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)
);

最新更新