diff --git a/README b/README new file mode 100644 index 0000000..e3aadbc --- /dev/null +++ b/README @@ -0,0 +1,10 @@ +# PyroCMS Related Posts Plugin + +The PyroCMS Related Posts plugin allows you to show a list of blog post headlines that use specified keywords. + +The idea behind this is that you can effortlessly add a small lex-based line of code to your pages to show posts that are tagged with related keywords. + +So for example, if you wanted to show the 5 latest posts that use the keywords "news" and "technology", you would do this: + +{{ related_posts:posts keywords="news,technology" maximum_posts="5" maximum_length="100" }} + diff --git a/related_posts.php b/related_posts.php new file mode 100644 index 0000000..1141940 --- /dev/null +++ b/related_posts.php @@ -0,0 +1,94 @@ + + * @copyright Copyright (c) 2012 Rick Mills + * + */ + +class Plugin_Related_Posts extends Plugin +{ + /** + * Posts + * + * Usage: + * {{ related_posts:posts keywords="keyword1,keyword2,keyword3,etc" maximum_posts="5" maximum_length="100" }} + * + * @return string (related posts are returned as part of a list and should be wrapped with 'ul' or 'ol' tags. + */ + function posts() + { + $keywords = $this->attribute('keywords'); + $maxposts = $this->attribute('maximum_posts'); + $maxlength = $this->attribute('maximum_length'); + + $keywordArray = explode(",", $keywords); + + $this->db->select('id'); + $this->db->from('keywords'); + $this->db->where_in('name', $keywordArray); + $result = $this->db->get(); + + $keywordIds = array(); + foreach($result->result() as $r) + { + $keywordIds[] = $r->id; + } + + if(!empty($result)) + { + $this->db->select('*'); + $this->db->from('keywords_applied'); + $this->db->where_in('keyword_id', $keywordIds); + $applied = $this->db->get(); + + if(!empty($applied)) + { + $hash_store = array(); + foreach($applied->result() as $a) + { + $hash_store[] = $a->hash; + } + + if(!empty($hash_store)) + { + // time to search the blog posts! + $this->db->select('*'); + $this->db->from('blog'); + $this->db->where_in('keywords', $hash_store); + $this->db->limit($maxposts); + $this->db->order_by('created_on', 'desc'); + $postQuery = $this->db->get(); + + $postString = ''; + + foreach($postQuery->result() as $post) + { + $postString .='
  • '.anchor('blog/'.date('Y/m', $post->created_on) .'/'.$post->slug, $this->neat_trim($post->title, $maxlength)).' - '.date('M jS Y', $post->created_on).'
  • '; + } + + return $postString; + } + } + } + } + + function neat_trim($str, $n, $delim='...') + { + $len = strlen($str); + if ($len > $n) + { + preg_match('/(.{' . $n . '}.*?)\b/', $str, $matches); + return rtrim($matches[1]) . $delim; + } + else + { + return $str; + } + } +} +/* End of file related_posts.php */ \ No newline at end of file