目录
在Wordpress文章后面列出相关文章,可以方便读者浏览更多相关的内容,通过下面的代码即可实现自动显示相关文章(按分类)。
首先,将下面的代码粘贴到你的主题functions.php文件中:
// "More from This Category" list by Barış Ünver @ Wptuts+
function wptuts_more_from_cat( $title = "More From This Category:" ) {
global $post;
// We should get the first category of the post
$categories = get_the_category( $post->ID );
$first_cat = $categories[0]->cat_ID;
// Let's start the $output by displaying the title and opening the <ul>
$output = '<div id="more-from-cat"><h3>' . $title . '</h3>';
// The arguments of the post list!
$args = array(
// It should be in the first category of our post:
'category__in' => array( $first_cat ),
// Our post should NOT be in the list:
'post__not_in' => array( $post->ID ),
// ...And it should fetch 5 posts - you can change this number if you like:
'posts_per_page' => 5
);
// The get_posts() function
$posts = get_posts( $args );
if( $posts ) {
$output .= '<ul>';
// Let's start the loop!
foreach( $posts as $post ) {
setup_postdata( $post );
$post_title = get_the_title();
$permalink = get_permalink();
$output .= '<li><a href="' . $permalink . '" title="' . esc_attr( $post_title ) . '">' . $post_title . '</a></li>';
}
$output .= '</ul>';
} else {
// If there are no posts, we should return something, too!
$output .= '<p>Sorry, this category has just one post and you just read it!</p>';
}
// Let's close the <div> and return the $output:
$output .= '</div>';
return $output;
}
之后,打开single.php文件,在适当位置添加调用函数:
<?php echo wptuts_more_from_cat( 'More From This Category:' ); ?>
原文地址:www.5che2.com
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。