Custom post type loop split/ordered by taxonomy

Check the below code-

// Initiating shortcode. Place this code to any of your page to get your desired output.
add_shortcode( 'faq_page_content', 'the_dramatist_faq_page_content');
/**
 * Rendering function
 */
function the_dramatist_faq_page_content() {
    $terms = get_terms('sections'); // Taxonomy name
    echo '<ul>';
    foreach($terms as $term) {
        $posts = get_posts(
            array(
               'post_type' => 'questions', // Post type
               'tax_query' => array(
                   array(
                       'taxonomy' => 'sections', // Taxonomy name
                       'field' => 'slug',
                       'terms' => $term->slug
                   )
               ),
               'posts_per_page' => -1
            )
        );
        echo '<li>' . $term->name;
        echo '<ul>';
        foreach($posts as $post) {
            echo '<li><a href="' . get_permalink( $post->ID ) . '">' . $post->post_title . '</a></li>';
        }
        echo '</ul></li>';
    }
    echo '</ul>';
}

Here we are initiating a shortcode called faq_page_content. Load this block of code through your plugin or functions.php and paste [faq_page_content] shortcode inside your desired page where you wanna show the FAQ’s. You’ll get your needed output.

Hope that helps.

Leave a Comment