0

Sorry New to this custom post and taxonomy thing I want help in displaying my custom post type arranged by taxonomy.

The output would be like:

  • Parent 1 Taxonomy Title
    • Child 1 Taxonomy Title
      • Title of a Post Under Child Taxonomy 1
      • Title of a Post Under Child Taxonomy 2
    • Child 2 Taxonomy Title
      • Title of a Post Under Child Taxonomy 1
      • Title of a Post Under Child Taxonomy 2
    • Child 3 Taxonomy Title
      • Title of a Post Under Child Taxonomy 1
      • Title of a Post Under Child Taxonomy 2
  • Parent 1 Taxonomy Title
    • Child 1 Taxonomy Title
      • Title of a Post Under Child Taxonomy 1
      • Title of a Post Under Child Taxonomy 2

currently I'm using this code

$custom_terms = get_terms('material_category');

foreach($custom_terms as $custom_term) {
    wp_reset_query();
    $args = array('post_type' => 'materials',
        'tax_query' => array(
            array(
                'taxonomy' => 'material_category',
                'field' => 'slug',
                'terms' => array('general-english')
            ),
        ),
     );

     $loop = new WP_Query($args);
     if($loop->have_posts()) {
        echo '<h2>'.$custom_term->name.'</h2>';

        while($loop->have_posts()) : $loop->the_post();
            echo '<a href="'.get_permalink().'">'.get_the_title().'</a>';
        endwhile;
     }

But it displays the Parent separately. Thanks in advance for the help :)

0

That's because you're echoing the Parent term name outside of the loop.

$custom_terms = get_terms('material_category');

foreach($custom_terms as $custom_term) {
    $args = array('post_type' => 'materials',
        'tax_query' => array(
            array(
                'taxonomy' => 'material_category',
                'field' => 'slug',
                'terms' => array('general-english')
            ),
        ),
    );

    $loop = new WP_Query($args);
    if ($loop->have_posts()) {
        while ($loop->have_posts()) : $loop->the_post();
            echo '<h2>' . $custom_term->name . '</h2>';
            echo '<a href="' . get_permalink() . '">' . get_the_title() . '</a>';
        endwhile;
    }
    wp_reset_query();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.