0

I'm trying to call the related posts of a custom post type by the category of the post that is loaded on the page.

Below is where I am at -

<?php                                               
    $blogcats = get_the_term_list();

    if (( 'post' == get_post_type() )) 
    {
        $posttypenews = 'post';
    }

    if (( 'blog' == get_post_type() )) 
    {
        $posttypenews = 'blog';
    }
?>
    <div id="news-related-posts-title" class="clear"><h1>Related Posts</h1></div>
      <?php
        $related = get_posts( array(    
            'numberposts' => 5,
            'blog_cats' => $blogcats,
            'post_type' => $posttypenews,
            'post__not_in' => array($post->ID)
        ) );
        if( $related ) foreach( $related as $post ) {
            setup_postdata($post);
      ?>

        <div id="news-related-posts">

            <div id="news-related-posts-container">

                <div id="news-related-posts-left">
                    <?php  the_post_thumbnail('thumbnail'); ?>
                </div>

                <div id="news-related-posts-right">
                    <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a>
                </div>
            </div>
        </div>

    <?php }
    wp_reset_postdata(); 
?>  

If I change $blogcats = get_the_terms(); to $blogcats = 'the tag_id'; is works, but I'm struggling to call it from the post thats loaded...

Am I missing something obvious?

Thanks in advance

1 Answer 1

1

get_the_term_list() returns HTML but you are trying to use it as if it returned a term ID -- 'blog_cats' => $blogcats,. That is not going to work. You will need to use get_the_terms() and a tax_query (I think. I am not 100% sure).

Something like:

$blogcats = get_the_terms($post->ID,'category');
// var_dump($blogcats);

$blogcats = wp_list_pluck($blogcats,'term_id');
// var_dump($blogcats);

$related = get_posts( 
  array(    
    'post_per_page' => 5,
    'tax_query' => array(
        array(
                'taxonomy' => 'category',
                'field'    => 'slug',
                'terms'    => $blogcats,
        )
    ),
    'post_type' => $posttypenews,
    'post__not_in' => array($post->ID) 
  ) 
);  
1
  • Might wanna throw an is_array in there - get_the_terms can return false. Commented Apr 17, 2015 at 10:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.