Related posts on tags

This is a small plugin that adds the capability of fetching posts that have the same or some of the same tags as the ones you send in through ajax as a JSON array. The plugin fetches the posts that match and then sorts them according to weight i.e. number of matching tags.

When I wrote the JSON part of the plugin I was a bit annoyed by wordpress's auto escape of quotes. After a bit of searching I found the function stripslashes_deep which is a wordpress function that reverts the changes of the auto addslashes.

The plugin is hooked on the ajax function search_tags

// Binding function rpot_search_on_tags to ajax hook
add_action('wp_ajax_search_on_tags', 'rpot_search_on_tags');
add_action('wp_ajax_nopriv_search_on_tags', 'rpot_search_on_tags');

If you want to search for posts and you want to use jquery, it's as simple as this;

var url = "";
var getVars = {
  action: "search_on_tags",
  tags: JSON.stringify( [
    'First tag',
    'My other tag',
    'The last tag'
  ] )

  function( response ){
    console.log( response );

The ajax response that you will get will look something like this:

// Response map
  date: "YYYY-MM-DD HH:MM:SS",    // String, Publish date
  image_full: [                   // Array, Original image (featured image)
    0:'http://',                // String, Url to image
    1:600,                      // Int, Image width
    2:200,                      // Int, Image height
    3:false                     // Boolean, Dunno, comes from wp_get_attachment_image_src()
  image_large: Array[4],          // Array, Large image, see above for description
  image_medium: Array[4],         // Array, Medium image, see above for description
  image_small: Array[4],          // Array, Small image, see above for description
  position: 0,                    // Int, Position in matches
  postid: 438,                    // Int, Post id
  timestamp: 1337893394,          // Int, Publish date as Unix timestamp
  title: "Post title",            // String, Post title
  url: "http://",                 // String, Permalink
  weight: 2                       // Int, Number of tag matches

And as always, go fetch the code, play with it! It's all for free on github!

Benjamin Horn
Benjamin Horn
Developer at Bazooka
A Finnish-German full-stack developer who's worked with a multitude of different technologies throughout the years.
Vaasa, Finland