will display unordered list with up to 3 related posts (the default value)
* will display unordered list with up to 7 related posts
*
* How to add related article to particular post?
* In post administration panel enter new Custom Field with meta name: hand_picked_article, and meta value: 123 (where 123 is related post ID)
* For more each one, add another Custom Field
*
* BTW, this software is free.
* by Creative Nights
*
*/
function cn_related_articles($max_articles = 3) {
global $post;
$cnt = 0;
$output = '';
$exclude_articles = $post->ID;
// 1. get handpicked articles
$hand_picked_articles = get_post_meta($post->ID, 'hand_picked_article', false);
if (is_array($hand_picked_articles)) {
foreach ($hand_picked_articles as $hand_picked_article => $hand_picked_article_id) {
$cnt++;
$exclude_articles .= ',' . $hand_picked_article_id;
$output .= '
' . get_the_title($hand_picked_article_id) . '' . "\n";
if ($cnt == $max_articles) break;
}
}
// 2. only if there’s not enough handpicked article
// get tag related articles
if ($cnt < $max_articles) {
$article_tags = get_the_tags();
$tags_string = '';
if ($article_tags) {
foreach ($article_tags as $article_tag) {
$tags_string .= $article_tag->slug . ',';
}
}
$tag_related_posts = get_posts('exclude=' . $exclude_articles . '&numberposts=' . $max_articles . '&tag=' . $tags_string);
if ($tag_related_posts) {
foreach ($tag_related_posts as $related_post) {
$cnt++;
$exclude_articles .= ',' . $related_post->ID;
$output .= '' . $related_post->post_title . '' . "\n";
if ($cnt == $max_articles) break;
}
}
}
// 3. only if there’s not enough tag related articles,
// get category related articles
if ($cnt < $max_articles) {
$article_categories = get_the_category($post->ID);
$category_string = '';
foreach($article_categories as $category) {
$category_string .= $category->cat_ID . ',';
}
$cat_related_posts = get_posts('exclude=' . $exclude_articles . '&numberposts=' . $max_articles . '&category=' . $category_string);
if ($cat_related_posts) {
foreach ($cat_related_posts as $related_post) {
$cnt++;
$output .= '' . $related_post->post_title . '' . "\n";
if ($cnt == $max_articles) break;
}
}
}
$output = '' . "\n" . '
Possibly related:
' . "\n" . '
' . "\n" . '
';
return $output;
}
?>