Question

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 on 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 posts with slug $cat_slug_course and none other

I feel this is something not-Wordpress-specific but PHP, which is why I post it here.

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; ?>

No correct solution

OTHER TIPS

Okay, it was more simple than expected.

<?php if ($cat_slug_course == $cat_slug): ?>
    <div class="landing_title">
        <?php the_title(); ?>
    </div>
        <?php the_content();?>
    </div>
<?php endif; ?>

Solves it. Did not expect that, but it does.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top