• Hi guys,

    In the sidebar of single.php i would like WordPress to display 3 related posts based on the categories assigned to the current post. Each post is usually assigned to about 3 or 4 multiple categories so the code needs to consider each.

    Previously i had got this to work perfectly based on tags, and the code is shown below. It needs tweaking to do the same thing but based on categories assigned, not tags. Any help is much appreciated. Thanks.

    <?php  //for use in the loop, list 3 post titles related to first tag on current post
    $backup = $post;  // backup the current object
    $tags = wp_get_post_tags($post->ID);
    $tagIDs = array();
    if ($tags) {
    $tagcount = count($tags);
    for ($i = 0; $i < $tagcount; $i++) {
    $tagIDs[$i] = $tags[$i]->term_id;
    }
    $args=array(
    'tag__in' => $tagIDs,
    'post__not_in' => array($post->ID),
    'showposts'=> 3,
    'orderby'=> 'rand',
    'caller_get_posts'=> 1
    );
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) { ?>
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • The topic ‘How to show related posts based on categories assigned?’ is closed to new replies.