<?php
function related_posts() {
global $wpdb, $post;
$pref = $wpdb->prefix;
$posttags = get_the_tags();
$postcats = get_the_category();
if ($posttags) {
foreach($posttags as $tag) {
$tag_in .= $tag->term_id.',';
}
$tag_in = substr($tag_in, 0, strlen($tag_in)-1 );
$intag = "$wpdb->term_taxonomy.term_id IN ( ".$tag_in." ) and ";
} else $intag = '';
if ($postcats) {
foreach ($postcats as $postcat) {
$cat_in .= $postcat->cat_ID.',';
}
$cat_in = substr($cat_in, 0, strlen($cat_in)-1 );
$incat = "wp_term_relationships.object_id in ( ";
$incat.= "select wp_term_relationships.object_id ";
$incat.= "from wp_term_taxonomy inner join wp_term_relationships on wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id ";
$incat.= "where wp_term_taxonomy.term_id in (".$cat_in.") ) and";
} else $incat = '';
$query = "select wp_term_relationships.object_id, wp_posts.post_title ";
$query.= "from wp_term_taxonomy inner join wp_term_relationships on wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id inner join wp_posts on wp_term_relationships.object_id=wp_posts.ID ";
$query.= "where ".$intag;
$query.= $incat." wp_posts.post_type LIKE 'post' and wp_posts.post_status LIKE 'publish' ";
$query.= "group by wp_term_relationships.object_id ";
$query.= "order by RAND() limit 5";
$rel_posts = $wpdb->get_results($query);
if (count($rel_posts) == 0) {
} else {
echo '<h3>Похожие новости</h3>';
echo '<ul>';
foreach ($rel_posts as $rel_post) {
echo '<li><a href="'.get_permalink($rel_post->object_id).'" >'.$rel_post->post_title.'</a></li>';
}
echo '</ul>';
}
}
?>