浏览量:91次
您的博客上有可靠的类别结构吗?如果是这样,您可能根本不需要“相关帖子”部分 - 您只需显示同一类别的最新帖子即可。
在这篇文章中,我们将介绍“此类别的更多内容”部分,这是“相关帖子”(我们之前介绍过)的替代选项。
如果您将帖子按类别组织得很好,您可能会发现拥有帖子类别中的帖子列表很有用。
“相关帖子”并不总是答案:如果您的网站上的帖子按类别分隔,那么“相关帖子”部分可能会“打破”这种分隔。
例如,如果您有一个关于不同职业群体的博客,则无法在有关信息学的帖子下将有关纺织行业的新闻显示为“相关新闻”。同一类别的许多最新帖子会更相关,对吧?
正如您可能已经猜到的,列出帖子类别中的最新帖子比根据帖子标签显示相关帖子要容易得多。我们只需要获取帖子的类别并列出该类别中的许多帖子,不包括访问者刚刚阅读的帖子。我们可以在 get_posts() 函数中传递的参数包含我们需要的一切。
<?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; } ?>登录后复制
[声明]本网转载网络媒体稿件是为了传播更多的信息,此类稿件不代表本网观点,本网不承担此类稿件侵权行为的连带责任。故此,如果您发现本网站的内容侵犯了您的版权,请您的相关内容发至此邮箱【915688610@qq.com】,我们在确认后,会立即删除,保证您的版权。
友情链接加载中...