在wordpress cpt中的子分类模板页面上获取父分类术语ID

Get parent taxonomy term id when on child taxonomy template page in wordpress cpt

我有一个带有分类法 "section" 的自定义 post 类型,我有一个带有查询循环的模板页面,用于显示带有缩略图的类别列表。我只想显示当前父分类的子类别,并希望在子页面上能够获取父类别的 ID。

我目前在我的代码中将父级设置为 id 40,但需要它是动态的。如何将 40 动态更改为当前父 ID?

这是我的分类模板页面中的代码。

<?php
      $terms  = get_terms( [
          'taxonomy'      => 'section',
          'parent'        => 40,
          'hide_empty'    => true,
          'relationship'  => [
              'id' => 'categories_to_posts',
              'to' => get_the_ID(), // You can pass object ID or full object
          ],
      ] );
      if ( $terms && ! is_wp_error( $terms ) ) {
      foreach ( $terms as $term ) {
        $term_link = get_term_link( $term->term_id );
        $term_name = $term->name;
        $url = get_term_meta( $term->term_id, 'kte_sec_thumbnail_image', true );
          echo '<img src="' . esc_url( $url ) . '">';
           $term = get_term_by( 'id', $child, $taxonomy_name );
           echo '<a href="' . esc_url( $term_link ) . '">' . $term_name . '</a>';
  }
  }

据我所知,您想在父分类页面上显示当前父分类的子项。所以使用这段代码来实现你的功能..

<?php 
$term123 = get_queried_object();
$slug=$term123->slug;
$parent_id  =$term123->parent;
$child_id=$term123->term_id;


$taxonomy_name ='section';
$termchildren  = get_term_children(  $child_id, $taxonomy_name  );
echo "<ul>";
foreach ( $termchildren as $child ) {
    $term = get_term_by( 'id', $child, $taxonomy_name );
?>
  <?php if ($term->parent == $child_id) { ?>

    <li><a href="<?php echo get_term_link($term->term_id); ?>"><?php echo $term->name; ?></a></li>
  <?php } 

  ?>

<?php } 
echo "</ul>";

?>