Get category of current post and use in "related" loop?

One a single page I want to list posts from another post-type but with the same cateogory, as related. How could I edit my loop to get the category of the current post and insert it in my related loop?

Code:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

..........

<?php endwhile; endif; ?>

..... here comes related posts .....

<?php
    $args = array(
        'post_type' => 'models',
        'car-category' => 'to-pros'
    );
    $the_query = new WP_Query( $args );
?>
<?php if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

    .......

<?php endwhile; endif; ?>

I had to do something similar in one of my client sites. The problem is determining the name of the category associated with the displayed post that is a custom post type. This is what I came up with -

// Determine the category name for the custom post type post 

         $post_id = $post->ID; 
                      
        $terms = get_the_terms($post_id, 'special_category');
   // 'special_category' should be replaced with the name of your custom taxonomy         
        if ( $terms && !is_wp_error( $terms ) ) : 
            
            foreach ( $terms as $term ) {
                $my_category = $term->name;  
            }
                       
        endif; 

Then do another WP_query with the other custom post type and the category name $my_category. That loop should pull up all the posts in the second post type with the same category name.

1 Like

Cool… can you tell me what is wrong with my code? I get “my_category indefined variable”.

    <?php

        $post_id = $post->ID; 

        $terms = get_the_terms($post_id, 'car-category');
        if ( $terms && !is_wp_error( $terms ) ) : 

            foreach ( $terms as $term ) {
                $my_category = $term->name;  
            }

        endif;

        $args = array(
            'post_type' => 'models',
            'car-category' => $my_category
        );
        $the_query = new WP_Query( $args );
    ?>
    <?php if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

After $post_id = $post->ID; add echo $post_id;

and after $terms = get_the_terms($post_id, 'car-category'); add print_r($terms); to test if your code really is picking up the correct Post ID and list of categories for that Post ID.

2 Likes

got it working, had forgotten to add a category to the current post…

thanks a lot for the help!=)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.