之前大叔介绍过 WordPress相关文章实现的方法,例:《代码实现WordPress相关文章》,那么今天说的这个教程,是从优化角度来更合理的实现WordPress相关文章的,至于客观喜欢哪个,自己决定吧!
策略:文章内容相关程度: 手动指定 > 标签 >分类 > 随机
实现方式:下面代码直接加到functions.php中即可
- function add_related_posts($content){
- return $content . wp_related_posts();
- }
- function wp_related_posts(){
- global $post;
- $num = 5;
- $counter = 1;
- $exclude_id = get_post_meta($post->ID,’related’,true);
- if ($exclude_id){
- $args = array(
- ‘post_type’ => array(‘post’),
explode(‘,’, $exclude_id),
- ‘posts_per_page’ => $num
- $posts = get_posts($args);
- foreach($posts as $sb){
- $output .= ‘<li><a href=“‘ . get_permalink($sb->ID) . ‘”>’ . $sb->post_title . ‘</a></li>’;
- $i++;
- }
- if( $i < $num){
- $tagsid = array();
- $catid = array();
- $thisid[] = $post->ID;
- $posttags = get_the_tags();
- $catids = get_the_category();
- if(!emptyempty($posttags)) {
- foreach($posttags as $tag) {
- $tagsid[] = $tag->term_id;
- }
- if(!emptyempty($catids)) {
- foreach($catids as $cat) {
- $catid[] = $cat->term_id;
- }
- $args = array(
- ‘post__not_in’ => $thisid,
- ‘posts_per_page’ => ($num – $i),
array(
- ‘relation’ => ‘OR’,
- array(
- ‘taxonomy’ => ‘post_tag’,
- ‘terms’ => $tagsid,
- array(
- ‘field’ => ‘term_id’,
$catid,
- ),
- );
- $rsp = get_posts($args );
- foreach($rsp as $sb){
- $output .= ‘<li><a href=“‘ . get_permalink($sb->ID) . ‘”>’ . $sb->post_title . ‘</a></li>’;
- $i++;
- }
- $final = ‘<h3>相关文章</h3><ul>’ . $output . ‘</ul>’;
- return $final;
-
如想自定位置,并调整样式,则去掉the_content
的钩子,然后手动调用wp_related_posts
函数
骚年,创作吧。。。。