Skip to content

Instantly share code, notes, and snippets.

@mrzlodey
Created October 6, 2015 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrzlodey/10512262aadcf1eb1e16 to your computer and use it in GitHub Desktop.
Save mrzlodey/10512262aadcf1eb1e16 to your computer and use it in GitHub Desktop.
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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment