使用wordpress的朋友都知道在日志下方显示相关文章,可以给访问者带来更好的体验,增加访客的浏览次数并降低访客的跳出率,同时对网站的seo也会有所帮助。网上调用相关文章的插件很多,但下面的代码可以帮助你免插件调用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:' ); ?>
原文:http://code.tutsplus.com/articles/quick-tip-after-the-content-more-from-this-category--wp-30696