How to Create a Simple Related Posts Plugin

I think it would be best to keep some things in a plugin. I have this code:

<div class="related-posts">

<h3>Related posts</h3>

<?php
    $orig_post = $post;
    global $post;
    $tags = wp_get_post_tags($post->ID);

    if ($tags) {
    $tag_ids = array();
    foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
    $args=array(
        'tag__in' => $tag_ids,
        'post__not_in' => array($post->ID),
        'posts_per_page'=>4, // Number of related posts to display.
        'caller_get_posts'=>1
    );

    $my_query = new wp_query( $args );

    while( $my_query->have_posts() ) {
    $my_query->the_post();
    ?>

    <div class="relatedthumb">
        <a rel="external" href="<? the_permalink()?>"><?php the_post_thumbnail(array(150,100)); ?><br />
        <?php the_title(); ?>
        </a>
    </div>

    <? }
    }
    $post = $orig_post;
    wp_reset_query();
?>
</div>

But I am not sure how to add it to a plugin. My main problem is I am not sure how to call this in my single.php…I know to add the class and function in the plugin and the basic setup, but other than that any advice is helpful 🙂

Related posts

1 comment

  1. Your code looks ok at a brief scan of the code. What you need is a plugin header comment, some way to wrap it up and prepare it for output and a way to call it in your templates.

    1. Plugin comment: The minimum thing you need is /* Plugin Name: Your plugins Name */
    2. Wrap your plugin in a function and add it a filter

      add_filter( 'your-filter-name', 'pluginCallback' );
      function pluginCallback()
      {
          // Your code without any echo or direct HTML tag calls *)
      }
      
    3. Then add it to your template:

      echo apply_filters( 'your-filter-name', "" );
      

    *) Instead of adding <div> HTML output directly, or echo DOM nodes (for e.g. echo '<div>';), simply put them into a string and return the result:

    $html = "";
    if ( $query->have_posts()  )
    {
        while ( $query->have_posts() )
        {
            $query->the_post();
    
            $html .= '<div class="relatedthumb">';
            $html .= sprintf( '<a href="%s" title="%s">%s</a>',
                get_the_permalink(),
                get_the_title(),
                get_the_post_thumbnail( /* args */ )
            );
            $html .= '</div>';
        }
    }
    // ... etc.
    return $html;
    

Comments are closed.