<?php
function show_previous_posts_from_category ($the_post_id, $the_category_id = 0, $post_num) {
$num = 0;
global $wpdb;
$sql = "SELECT wposts.*
FROM $wpdb->posts wposts
LEFT JOIN $wpdb->term_relationships ON (wposts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE $wpdb->term_taxonomy.taxonomy = 'category'
AND $wpdb->term_taxonomy.term_id = '$the_category_id'
AND wposts.post_status = 'publish'
AND wposts.post_type = 'post'
AND wposts.ID < '$the_post_id'
ORDER BY wposts.ID DESC
LIMIT $post_num";
$result = $wpdb->get_results($sql, OBJECT);
global $post;
?>
<h2>Похожие записи:</h2>
<ul>
<?php
foreach ($result as $post) {
setup_postdata($post);
?>
<li>
<h4>
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title() ?></a>
</h4>
<a href="<?php the_permalink() ?>" rel="bookmark" >
Здесь функция вывода изображений (в зависимости от того, как вы выводите их на своем сайте)
</a>
</li>
<?php
$num++;
$save_ids[] = $post->ID;
}
if ( $num < $post_num || !$result ) {
$need_more = $post_num-$num;
$save_ids[] = $the_post_id;
$save_ids = join (',', $save_ids);
$more_posts = get_posts("numberposts=$need_more&category=$the_category_id&exclude=$save_ids");
foreach ($more_posts as $post){
setup_postdata($post);
?>
<?php } } ?>
</ul>
<?php } ?>
<?php
$the_cat = get_the_category();
$the_cat_id = $the_cat[0]->cat_ID;
show_previous_posts_from_category($post->ID, $the_cat_id, 3);
wp_reset_query();
?>