Tommy Adeniyi
Tommy Adeniyi

Reputation: 335

Query to get learndash topics

I have a learndash site with a few courses each with subtopics to make up the course. I need to generate a list of published courses and the subtopics under them. My query for getting the courses:

$args= array('post_type' => 'sfwd-courses',
            'post_status' => 'publish',
            'order' => 'DESC',
            'orderby' => 'ID',
            'mycourses' => false);
$loop = new WP_Query( $args );
 while ( $loop->have_posts() ) : $loop->the_post();
    endwhile;

This returns the published courses. Now I need to get the subtopics under each course. The post type for the topics is "sfwd-topic" but I dont understand how the 2 are related so I can query it.

Upvotes: 1

Views: 2603

Answers (1)

Carl Elder
Carl Elder

Reputation: 114

Few ways I've done this. This would be the easiest I know of if you're not going into sub-sub-sub topics or anything like that.

You'll need to run a second query for the topics themselves. If you're not going more than 2 levels deep or your sub-topics don't reach into the hundreds for each course, you shouldn't experience any performance issues.

Inside of your while loop, build the array $argsTwo, just like you did $args, and set 'post_type' => 'sfwd-topic'.

$argsTwo = array('post_type' => 'sfwd-topics',
    'post_status' => 'publish',
    'order' => 'DESC',
    'orderby' => 'ID',
 );

Then, add another while loop and move through the sub-topics.

while ( $loop->have_posts() ) : $loop->the_post();
    $argsTwo = array('post_type' => 'sfwd-topics',
        'post_status' => 'publish',
        'order' => 'DESC',
        'orderby' => 'ID',
    );
    $loopChild = new WP_Query( $argsTwo );
    while ( $loopChild->have_posts() ) : $loopChild->the_post();
    endwhile;
endwhile;

This will get the sub-topics for the current post, which is one of your courses. Echo the posts values you need in the format you like.

When your parent loop moves to the next post, it will go through the child loop again to get all of the sub-topics for your new post. Good luck!

EDIT Almost forgot, the new query will get all topics, not related ones without referencing the parent in $argsTwo.

You need to add the parent ID to the 'post_parent' key in $argsTwo, like so:

$argsTwo = array(
    'post_type' => 'sfwd-topic',
    'post_status' => 'publish',
    'order' => 'DESC',
    'orderby' => 'ID',
    'post_parent' => $loop->ID
);

Upvotes: 1

Related Questions