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.
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.