WordPress文章内容底部添加相关文章
这个功能貌似很多人都已经知道了,但是我相信还是有很多新接触 WordPress 的用户还是不了解的,这里我就直接简单的说明一下,不明白的地方可以直接留言。
我们将下面的代码直接添加到functions.php中最后一个?>之前即可:
function more_from_cat( $title = "相关文章" ) {
global $post;
$categories = get_the_category( $post->ID ); //确定当前文章所属分类
$first_cat = $categories[0]->cat_ID; //当出现多分类的时候选择第一个分类
$output = '<div id="more-from-cat"><h3>' . $title . '</h3>'; //相关文章标题
$args = array(
'category__in' => array( $first_cat ), //文章筛选
'post__not_in' => array( $post->ID ), //当前文章不在列表中显示
'posts_per_page' => 5 //每页显示五篇文章
);
$posts = get_posts( $args );
if( $posts ) {
$output .= '<ul>';
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>'; //list内容输出
}
$output .= '</ul>';
} else {
$output .= '<p>抱歉,目前该分类还没有相关文章</p>';
}
$output .= '</div>';
return $output;
}
代码部分需要作出解释的我已经做出了解释了,其余的部分,大家可以自行理解的还是可以通过百度来了解的。添加了上面的代码之后,我们还需要在指定位置添加下面的调用代码:
<?php echo more_from_cat( '相关文章' ); ?>
那么指定位置在哪里,这个真心不好说,你喜欢添加在评论上方,那么就去评论的模板上面添加,喜欢在文章主题内容下方,那么就去主体部分下面加,不同主题自然添加位置不一样,没有一个标准。
VIA:BanYuner
- 我的微信
- 这是我的微信扫一扫
-
- 我的微信公众号
- 我的微信公众号扫一扫
-





