How to relate one custom post type to another custom post type

Your data organisation is not perfect, which is why you’re faced with the current predicament.

Instead of 2 post types and a taxonomy, use 2 taxonomies and 2 post types

  1. Subject Categories ( taxonomy )
  2. Question Sets ( taxonomy )
  3. Exam ( post type )
  4. MCQ’s ( post type )

Assign MCQ’s to a question set, and assign exams to both subject categories and question sets.

When in a subject category archive, list exam post types. When in an exam post, list any MCQ’s that share the question set of the current post.

This allows you flexibility, such as sharing questions between exams, changing a question that appears in multiple exams once to fix them all, less unnecessary duplication, etc

In single-exam.php:

$terms = get_the_terms( $post->ID, 'question-sets' );

if ( $terms && ! is_wp_error( $terms ) ) :{

    foreach ( $terms as $term ) {
        $q = new WP_Query('post_type' => 'mcq','question-sets' => $term->name);
        if($q->have_posts()){
            while($q->have_posts()){
                $q->the_post();
                get_template_part('single','mcq');
            }
        }
        wp_reset_postdata();
    }
}

Where single-mcq.php contains the html for an individual mcq.