I have 2 Custom Post types "Sections" and "Articles". I want to create sidebar navigation using this two post type.
"Section" custom post type is just simple post with page title which is ACF relationship field in Article custom post type.
Article is hierarchical custom post type which can have muli-level of children posts
I got success to get all post matching section_group meta value(post_title of section custom post type) but I want to show them in hierarchical structure until there is no child post.
In below structure 1,2,3 are page_titles form Sections. Under that all the articles has AFC custom filed (Relationship).
E.g
Getting Started
- Parent Article 1
- Child Article
- Great-grandchild Article
- Child Article
- Child Article
- Parent Article 2
- Parent Article 1
What You'll Need
- Parent Article 1
- Child Article
- Child Article
- Great-grandchild Article
- Child Article
- Parent Article 2
- Parent Article 3
- Parent Article 1
How It'll Work
- Parent Article 1
- Child Article
- Great-grandchild Article
- Great-grandchild Article
- Great-grandchild Article
- Child Article
- Great-grandchild Article
- Child Article
- Child Article
- Child Article
- Parent Article 1
I wish to have structure like above.
Below is the code where first I queried Section Custom post type
then I matched that with article's ACS relationship using meta_value
Which gives me all child and grandchild posts in same LI.
<?php
$sections = new WP_Query(
array(
'posts_per_page' => -1,
'post_type' => 'sections',
'order' => 'ASC',
)
);
if ( $sections->have_posts() ) : ?>
<ul class="list-unstyled main">
<?php while ( $sections->have_posts() ) :
$sections->the_post(); ?>
<li>
<?php the_title() // Page title from Section Custom post Type ?>
<?php $section_id = get_the_ID();
$articles = new WP_Query(
array(
'posts_per_page' => -1,
'post_type' => 'articles',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'section_group',
'value' => $section_id,
'compare' => 'LIKE'
)
)
)
); ?>
<ul class="list-unstyled sub">
<?php
if ( $articles->have_posts() ) :
while ( $articles->have_posts() ) :
$articles->the_post(); ?>
<li class="this"><a href="<?php the_permalink(); ?>"><?php the_title() ?></a></li>
<!-- Sub LI Ends -->
<?php endwhile;
endif; ?>
</ul> <!-- Sub UL Ends -->
</li> <!-- Main LI Ends-->
<?php endwhile; ?>
</ul> <!-- Main UL Ends -->
<?php endif;
?>