Display posts with current tag by category

I’m creating a list of posts that have the same tag as the current post (this is in a single-post template). I need to display those posts organized by category, with the category name appearing once as a header. So the end result will simply be:

CATEGORY1
POST1
POST2
POST3
CATEGORY2
POST4
POST5
POST6

Read More

etc… All posts having the same tag as the current post, organized by category, with the category name displaying once. (All posts having this tag will only belong to one category. The current post will only have one tag.) Because of other loops on the template, this needs to use WP_Query. My PHP skills are minimal—I’ve spent several days searching for a solution, and have found bits and pieces that are helpful, but I’ve not been able to solve this problem. Any help is much appreciated.

Related posts

1 comment

  1. You need to fetch current post tags and all posts associated with those tags. This can be done as follows,

      global $post;
    
      $tags = wp_get_post_tags(get_the_ID());
    
      if ($tags) {
    
                    $tag_list = wp_get_object_terms(get_the_ID(),'post_tag',array('fields' => 'ids'));
    
                    $post_args = array(
                        'orderby' => 'post_date',
                        'order' => 'DESC',
                        'post_type' => 'post',
                        'post_status' => 'publish',
                        'posts_per_page' => 5,          
                        'post__not_in' => array( $post->ID ),
                        'tag__in' => $tag_list
                    );
    
          $get_recent_posts = get_posts($post_args);
    
       }//if ends - tags present
    

    This will fetch 5 Recent posts excluding current post.

    We can include following code in above block, to sort posts by category as follows,

        $post_arr = array();
    
        foreach($get_recent_posts as $recent_post)
        {
            $post_id = $recent_post->ID;
    
            $category_id_list = wp_get_post_categories($post_id);
    
            $current_category_id = current($category_id_list);
    
            if(array_key_exists($current_category_id,$post_arr))
            {
    
                array_push($post_arr[$current_category_id],$post_id);
            }
            else
            {
                $post_arr[$current_category_id] = array($post_id);
            }
        }
    

    This will generate output as below,

     Array
     (
       [69] => Array
        (
            [0] => 135
        )
    
        [70] => Array
        (
            [0] => 140
            [1] => 8
        )
    
      )
    

    like, Category ID as ‘key’ & all other associated post ids as its element.

Comments are closed.