single.php
<div class="related_posts">
<h4>Читайте также:</h4>
<?php
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'showposts' => '5',
'orderby' => 'rand',
'ignore_sticky_posts' => '1',
'no_found_rows' => true,
'cache_results' => false
);
$my_query = new wp_query($args);
if( $my_query->have_posts() ) {
echo '<ul>';
while ($my_query->have_posts()) {
$my_query->the_post();
?>
<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
<?php
}
echo '</ul>';
}
wp_reset_query();
}
?>
</div>Строка
'showposts' => '5',
отвечает за количество выводимых записей.
Строка
'orderby' => 'rand',
Позволяет выводить записи в случайном порядке. При её отсутствии будут выводиться последние записи.
Исключить рубрику по id:
'category__not_in' => '10',
Для того, чтобы исключить несколько рубрик можно использовать массив:
'category__not_in' => array(10,11),
Для вывода с миниатюрами заменить на:
<li><a href="<?php the_permalink() ?>"><?php the_post_thumbnail('thumbnail'); ?><?php the_title(); ?></a></li>и добавить CSS для горизонтального списка:
.related_posts li {
list-style-type: none;
float: left;
width: 220px;
}Если тема не поддерживает вывод миниатюр, в файл functions.php нужно добавить:
if ( function_exists( 'add_theme_support' ) ) {
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 200, 150, true );
}где 200, 150 — ширина и высота миниатюры.
Все изменения удобней произвести в дочерней теме.
Результат - ниже ↓
Ещё вариант (без миниатюр):
Добавить в functions.php
function related_posts($title = 'Related Posts', $count = 5) {
global $post;
$tag_ids = array();
$current_cat = get_the_category($post->ID);
$current_cat = $current_cat[0]->cat_ID;
$this_cat = '';
$tags = get_the_tags($post->ID);
if ( $tags ) {
foreach($tags as $tag) {
$tag_ids[] = $tag->term_id;
}
} else {
$this_cat = $current_cat;
}
$args = array(
'post_type' => get_post_type(),
'numberposts' => $count,
'orderby' => 'rand',
'tag__in' => $tag_ids,
'cat' => $this_cat,
'exclude' => $post->ID
);
$related_posts = get_posts($args);
if ( empty($related_posts) ) {
$args['tag__in'] = '';
$args['cat'] = $current_cat;
$related_posts = get_posts($args);
}
if ( empty($related_posts) ) {
return;
}
$post_list = '';
foreach($related_posts as $related) {
$post_list .= '<li><a href="' . get_permalink($related->ID) . '">' . $related->post_title . '</a></li>';
}
return sprintf('
<div class="related-posts">
<h4>%s</h4>
<ul>%s</ul>
</div> <!-- .related-posts -->
', $title, $post_list );
}
/**
* Настройки отображения для похожих записей
*/
add_action('genesis_after_post_content', 'do_related_posts');
function do_related_posts() {
//Заголовок
$title = 'Читайте также:';
//Показываем только для отдельной записи
if ( !is_single() ) {
return;
}
/** При желании можно указать тип записей, для которых не будут отображаться ссылки
* $exclude = array('aeprofiles', 'bizdir', 'palettes');
* foreach($exclude as $type) {
* if ( get_post_type() == $type ) {
* return;
* }
* }
*/
echo related_posts($title);
}В зависимости от ваших потребностей, скрипт можно изменить под свои нужды: изменить количество отображаемых ссылок (строка 1), задать параметры сортировки (строка 18). По умолчанию похожие записи отображаются в случайном порядке, вы можете изменить параметры сортировки на одно из значений ниже:
rand — случайно;
title — по названию;
date — по дате публикации;
modified — по дате последнего изменения.
Для отображения похожих записей, необходимо добавить в файл content.php код вызова нашей функции.
<?php do_related_posts(); ?>
CSS:
.related-posts {
/* ... */
}
.related-posts h4 {
/* ... */
}
.related-posts ul li {
/* ... */
}
.related-posts a {
/* ... */
}Ещё вариант только для меток (с миниатюрами и датой)
single.php:
<?php $orig_post = $post;
global $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args=array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=>5, // Number of related posts that will be shown.
'caller_get_posts'=>1
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
echo '<div id="relatedposts"><h3>Related Posts</h3><ul>';
while( $my_query->have_posts() ) {
$my_query->the_post(); ?>
<li><div class="relatedthumb"><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_post_thumbnail(); ?></a></div>
<div class="relatedcontent">
<h3><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
<?php the_time('M j, Y') ?>
</div>
</li>
<? }
echo '</ul></div>';
}
}
$post = $orig_post;
wp_reset_query(); ?>Только для категорий (с миниатюрами и датой) :
<?php $orig_post = $post;
global $post;
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=> 2, // Number of related posts that will be shown.
'caller_get_posts'=>1
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
echo '<div id="related_posts"><h3>Related Posts</h3><ul>';
while( $my_query->have_posts() ) {
$my_query->the_post();?>
<li><div class="relatedthumb"><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_post_thumbnail(); ?></a></div>
<div class="relatedcontent">
<h3><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
<?php the_time('M j, Y') ?>
</div>
</li>
<?
}
echo '</ul></div>';
}
}
$post = $orig_post;
wp_reset_query(); ?>Для вывода в случайном порядке добавить в эту часть кода 'orderby' => 'rand':
$args=array( 'category__in' => $category_ids, 'post__not_in' => array($post->ID), 'posts_per_page'=> 2, // Number of related posts that will be shown. 'caller_get_posts'=>1, 'orderby' => 'rand' );