0
votes

I'm trying to set up related posts that show posts in the same category as the current. The way the clients blog is set up is that they all share the category "blog", the related posts will show the same thing for every post.

<?php $related = get_posts( array( 
                'category__in' => wp_get_post_categories($post->ID), 
                'numberposts' => 4, 
                'post__not_in' => array($post->ID)
                ) );

            ?> 

I need to get posts that aren't the primary category (Blog). I can't do "cateogry__not__in" because then it would exclude everything.

2
How about filtering wp_get_post_categories($post->ID) so it doesn't include the blog-category? - janh
Can you help me go about this? I still need to make sure it's not hiding posts with category blog because they all have that category. - corporalpoon
'category__in' => array_diff( wp_get_post_categories($post->ID), array(5) ),.... (where 5 is the ID of the blog category....) - random_user_name
Thanks, cale, but it's still returning the same set of posts for every single.php post - corporalpoon
Well, then it sounds like your posts all are within these categories, yes? Unless you troubleshoot - share ID's of categories - the ID's of the categories for the current post, etc., this is impossible to guess. - random_user_name

2 Answers

0
votes

According to wp_term_query's docs, you should be able to exclude the blog by adding parameters, e.g. changing your category__in to

'category__in' => wp_get_post_categories(
    $post->ID,
    array(
        "exclude" => array($blogid)
    )
),

with $blogid being the term id of your blog category. Since it also provides exclude_tree to exclude terms and their child terms, I assume that it will do exactly what you want to achieve and exclude only the blog category.

0
votes

Okay, I think I found a way. Everything seems to function the way I want.

 $categories = get_the_category();
 $category_filter = array();

   foreach ($categories as $category) {
     if ($category->name != "Blog") {
        array_push($category_filter, $category->term_id);
     }
  }



    <?php $related = get_posts( array( 
         'category__in' => $category_filter,
          'numberposts' => 4, 
           'post__not_in' => array($post->ID),
            'orderby' => 'rand'
       ) );

     ?>