0

I tried to display post with links by sub term and group thouse posts and sub terms by parent terms. For example:

Parent term 1

  • Parent term 1

    Term 1

    • Post1
    • Post2
    • Post3

    Term 2

    • Post4
    • Post5
  • Parent term 2

    Term 3

    • Post6
    • Post7

Instead of this I receive:

  • Term 1

    • Post1
    • Post2
    • Post3
    • Post4
    • Post5
    • Post6
    • Post7

    Term 2

    • Post1
    • Post2
    • Post3
    • Post4
    • Post5
    • Post6
    • Post7

    Term 3...

Here is my current code:

$all_terms = get_terms(['taxonomy' => 'course-category', 'hide_empty' => 1 ] );
if (!$all_terms){
    $Content = '<h2>no terms</h2>';;
    
}
foreach (  $all_terms as $term ) { // external
    $query = new WP_Query( [
        'post_status' => 'publish',
        'post_type' => 'course'
        
        
    ]);
    if ( ! $query->have_posts() ) continue;
    $Content .= '<h3>' . $term->name . '</h3>';
    $Content .= "<div>";
    while ( $query->have_posts() ) {// internal
        $query->the_post();
        $Content .= '<li><a href="'. get_permalink() .'">'. get_the_title() .'</a></li>';
        
       
    }
    $Content .= "</div>";

I don't realy understand how to use get_terms(), and maybe, get_term_children() for deal with this.

Help me please to solve this ... I'll be grateful for any advice you can share. Thanks.

1 Answer 1

0

I don't realy understand how to use get_terms(), and maybe, get_term_children() for deal with this.

I believe you're missing 3 important pieces of information:

  • terms that have no parent have a parent ID of 0
  • you can ignore get_term_children, just use the parent parameter of get_terms
  • for this to work more than one or two levels deep you will need to put this in a recursive function or you'll just end up with tonnes of nested loops

get_terms takes the same arguments as WP_Term_Query, I strongly recommend reading through the available arguments on the official documentation:

https://developer.wordpress.org/reference/classes/wp_term_query/__construct/

Likewise, all of this would have been explained with examples in the comments for the official get_terms documentation page:

https://developer.wordpress.org/reference/functions/get_terms/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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