图片待添加
图片待添加

WordPress主题开发教程:文章详细页面调用当前文章的前5篇和后5篇文章

WordPress主题的文章详细页面的底部一般会调用上一篇文章与下一篇文章.

同时下面还会调用你可能感兴趣的文章:

WordPress主题开发教程:纯代码显示文章底部可能感兴趣相关文章推荐列表

比如这样:

WordPress主题开发教程:文章详细页面调用当前文章的前5篇和后5篇文章

当然也会有朋友想调用当前文章的前5篇和后5篇文章

实现方式:

将以下的PHP代码放到自己网站模板的函数文件functions.php中:

function wpyi_get_post( $previous = true, $number = 1 ) {    
       
//global当前文章变量 $post 和数据库操作类wpdb    
global $post, $wpdb;    
if ( emptyempty( $post ) )    
  return null;    
   
$current_post_date = $post->post_date;//当前文章的时间    
   
$join = '';    
$posts_in_ex_cats_sql = '';    
//加入表    
$join = " INNER JOIN $wpdb->term_relationships AS tr ON p.ID = tr.object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id";    
//获取当前文章所属分类,可以同属多个分类,如果是自定义的分类法,将category换成对应的分类法即可    
$cat_array = wp_get_object_terms($post->ID, 'level', array('fields' => 'ids'));    
$join .= " AND tt.taxonomy = 'level' AND tt.term_id IN (" . implode(',', $cat_array) . ")";    
   
//判断时间是大于还是小于    
$op = $previous ? '<' : '>';    
//排序    
$order = $previous ? 'DESC' : 'ASC';    
     
$where = $wpdb->prepare("WHERE p.post_date $op %s AND p.post_type = %s AND p.post_status = 'publish' ", $current_post_date, $post->post_type);    
$sort  = "ORDER BY p.post_date $order LIMIT 0, $number";    
   
$query = "SELECT p.* FROM $wpdb->posts AS p $join $where $sort";    
$query_key = 'adjacent_post_' . md5($query);    
$result = wp_cache_get($query_key, 'counts');    
if ( false !== $result )    
  return $result;    
   
$result = $wpdb->get_results("SELECT p.* FROM $wpdb->posts AS p $join $where $sort");    
if ( null === $result )    
  $result = '';    
wp_cache_set($query_key, $result, 'counts');    
return $result;    
}

在你的WordPress主题的single.php页面(文章详细页面)
的底部添加如下代码:

<h3>前几篇文章</h3>    
<ul>    
<?php    
$preposts = v7v3_get_post(true,3);    
foreach( $preposts as $postt ){    
  echo '<li><a href="'.get_permalink($postt->ID).'" title="'.$postt->post_title .'">'.$postt->post_title .'</a></li>';    
};    
?>    
</ul>    
<h3>后几篇文章</h3>    
<ul>    
<?php    
$nextposts = wpyi_get_post(false,3);    
foreach( $nextposts as $postt ){    
  echo '<li><a href="'.get_permalink($postt->ID).'" title="'.$postt->post_title .'">'.$postt->post_title .'</a></li>';    
};    
?>    
</ul>

代码的样式请自己修改;

当然你也可以加入文章缩略图调用,让WordPress主题的样式更丰富;


本文地址: https://www.wpyi.com/the-first-5-articles.html