Created
October 6, 2015 11:24
-
-
Save mrzlodey/10512262aadcf1eb1e16 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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