Title: Shortcode for related posts
Last modified: February 10, 2017

---

# Shortcode for related posts

 *  [ata24](https://wordpress.org/support/users/ata24/)
 * (@ata24)
 * [9 years, 3 months ago](https://wordpress.org/support/topic/shortcode-for-related-posts/)
 * _[ Moved to the [Fixing WordPress sub-forum](https://wordpress.org/support/topic/before-posting-in-everything-wordpress/).]_
 * Hello,
    I’m using bellow function for related post shortcode and I have two question
   about it, first: it’s supposed to display posts with related tag but it doesn’t
   do that what’s wrong?. Second: how the code should be changed so I can use something
   like `[rps tag=google]` and the function just return a post has a tag as “google”?
   This is the code:
 *     ```
       add_shortcode('rps', 'fphp_get_related_posts');
       function fphp_get_related_posts() {
           $reset_post = $post;
           global $post;
           $post_tags = wp_get_post_tags($post->ID);
   
           if ($post_tags) {
               $post_tag_ids = array();
           foreach($post_tags as $post_tag) $post_tag_ids[] = $post_tag->term_id;
               $args=array(
                   'tag__in' => $post_tag_ids,
                   'post__not_in' => array($post->ID),
                   'posts_per_page' => 1,
             		'orderby' => 'rand',
               );
   
           $related_query = new wp_query( $args );
           if (intval($related_query->post_count) === 0) return '';
   
           $html = '<div class="rps"><ul><h3>همچنین بخوانید</h3>';
             $related_query->the_post();
             $html .= '<li style="width:250px">';
             $html .= '<div class="relatedthumb"><a rel="external" href="'. get_the_permalink(). '">';
             $html .= get_the_title() . '</a>';
             $html .= '</div></li>';
         }
         $post = $reset_post;
         wp_reset_query();
   
         $html .= '</ul></div>';
         return $html;
       }
       ```
   

The topic ‘Shortcode for related posts’ is closed to new replies.

## Tags

 * [shortcode](https://wordpress.org/support/topic-tag/shortcode/)

 * In: [Fixing WordPress](https://wordpress.org/support/forum/how-to-and-troubleshooting/)
 * 0 replies
 * 1 participant
 * Last reply from: [ata24](https://wordpress.org/support/users/ata24/)
 * Last activity: [9 years, 3 months ago](https://wordpress.org/support/topic/shortcode-for-related-posts/)
 * Status: not resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
