I solved the problem of displaying from a custom post type in a post with this solution, however, I want to filter even more and only display the posts from custom post type that match the main post’s category (or to be more precise the slug, but there’s no difference in solution).
I get the slug of the main post by using this:
$category_main = get_the_category();
$cat_slug = $category_main[0]->slug;
echo $cat_slug; // This is just to see if I got the right output
I get the slug from the custom post type in the same way, but it’s within a loop that loops through the custom post types.
$category_course = get_the_category();
$cat_slug_course = $category_course[0]->slug;
echo $cat_slug_course;
So, what I want now, is to only display the posts from the custom type that match the slug of the original post.
In pseudo-code this would be something like:
If $cat_slug_course is equal to $cat_slug, display all custom type posts with slug $cat_slug_course and none other
This is the loop used to display the custom type posts.
$args = array( 'post_type' => 'Course', 'posts_per_page' => 2 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$category_course = get_the_category();
$cat_slug_course = $category_course[0]->slug;
echo $cat_slug_course; // This is just to see if I got the right output
echo '<br />';
the_title();
echo '<div class="entry-content">';
the_content();
echo '</div>';
endwhile; ?>
A better solution than the one you found on your own, would be to only retrieve matching posts in the first place. As is, you are potentially retrieving the wrong data. With your code (your solution), what happens if the two posts in the result set don’t match? You get no output at all.
Your description/code is a bit disjointed so I am guessing at things a little, and this is untested, but I think that what you want is:
Okay, it was more simple than expected.
Solves it. Did not expect that, but it does.