Как вывести предыдущие записи из той же рубрики в wordpress

Для того, чтобы добавить предыдущие записи из той же рубрики, что и текущий пост, совсем не обязательно использовать плагины, как известно они вызывают дополнительную нагрузку. Чтобы вывести предыдущие записи на странице wordpress, необходимо в файл single.php вашей темы добавить следующий код, в то место где нужно вывести похожие записи.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?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;
?>
<ul>
<?php
foreach ($result as $post) {
setup_postdata($post);
?>
<li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></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);
?>
<li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?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, 5);
wp_reset_query();
?>

 

Добавить комментарий