【问题标题】:Want to Get Parent Category Name than Child Category Name than post title想要获取父类别名称而不是子类别名称而不是帖子标题
【发布时间】:2021-09-03 21:31:50
【问题描述】:

如何在 WordPress 自定义帖子类型中获得以下内容

  1. 父类别名称 1

    1. 子类别名称 1
      1. 帖子标题
      2. 帖子标题
    2. 子类别名称 2
      1. 帖子标题
      2. 帖子标题
  2. 父类别名称 2

    1. 子类别名称 1
      1. 帖子标题
      2. 帖子标题
    2. 子类别名称 2
      1. 帖子标题
      2. 帖子标题

【问题讨论】:

    标签: wordpress


    【解决方案1】:

    您可以使用以下代码:

    <?php 
    $parent_terms = get_terms( array( 'taxonomy' => 'taxonomy_name', 'parent' => 0 ) );
    
    if(!empty($parent_terms)){
        
        foreach($parent_terms as $parent_term){
            echo $parent_term->name;
    
            $termchildrens = get_terms('taxonomy_name',array('child_of' => $parent_term->term_id));
            if(!empty($termchildrens)){
    
                foreach($termchildrens as $termchildren){
    
                    echo $termchildren->name;
                    $args = array(
                        'post_type' => 'cpt_name',
                        'tax_query' => array(
                            array(
                            'taxonomy' => 'taxonomy_name',
                            'field' => 'term_id',
                            'terms' => $termchildren->term_id
                            )
                        )
                    );
                    $the_query = new WP_Query( $args );
    
                    if ( $the_query->have_posts() ) {
                        while ( $the_query->have_posts() ) {
                            $the_query->the_post();
                            echo get_the_title();
                        }
                    } else {
                        // no posts found
                    }
                    wp_reset_postdata();
                }
            }
        }
    }
    ?>
    

    【讨论】:

      猜你喜欢
      • 2012-09-18
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-22
      • 1970-01-01
      • 2016-06-25
      相关资源
      最近更新 更多