previous_posts_link() 與 next_post_lnik() 這兩個函數相信各位 WordPress 主題開發者一定不陌生,這兩個函數是 WordPress 用來調用當前文章的前一篇以及後一篇文章的。但是有些時候我們為了提高網站 PV 提高用户體驗想多調用幾篇文章,例如調用當前文章的前三篇文章以及後三篇文章那該怎麼調用呢?查看了下 WordPress 的官方文檔,顯然沒有現成的代碼和函數可用。那麼只好自己動手豐衣足食了。以下代碼參考自 WordPress 默認函數 get_adjacent_post 函數修改而來:

  1. function ztmao_get_post( $previous = true, $number = 1 ) {
  2. global $post, $wpdb;
  3.     if ( emptyempty( $post ) )
  4. return null;
  5. $current_post_date = $post->post_date;
  6. $join = '';
  7.     $posts_in_ex_cats_sql = '';
  8.     $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";
  9.     $cat_array = wp_get_object_terms($post->ID, 'level', array('fields' => 'ids'));
  10. $join .= " AND tt.taxonomy = 'level' AND tt.term_id IN (" . implode(',', $cat_array) . ")";
  11.     $op = $previous ? '<' : '>';
  12.     $order = $previous ? 'DESC' : 'ASC';
  13.     $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);
  14. $sort  = "ORDER BY p.post_date $order LIMIT 0, $number";
  15. $query = "SELECT p.* FROM $wpdb->posts AS p $join $where $sort";
  16.     $query_key = 'adjacent_post_' . md5($query);
  17. $result = wp_cache_get($query_key, 'counts');
  18.     if ( false !== $result )
  19. return $result;
  20. $result = $wpdb->get_results("SELECT p.* FROM $wpdb->posts AS p $join $where $sort");
  21.     if ( null === $result )
  22. $result = '';
  23.     wp_cache_set($query_key, $result, 'counts');
  24. return $result;
  25. }

將該函數放在主題的 functions.php 文件中即可,調用該函數的時候會返回一個數組,使用示例:

  1. <h4> 本篇教程之前的幾篇教程是</h4>
  2.             <?php
  3. $preposts = v7v3_get_post(true,3);
  4.             foreach( $preposts as $postt ){
  5. echo '<li><a href="'.get_permalink($postt->ID).'" title="'.$postt->post_title .'">'.$postt->post_title .'</a></li>';
  6.             };
  7.             </ul>
  8.             <ul>
  9.             $nextposts = ztmao_get_post(false,3);
  10. foreach( $nextposts as $postt ){
  11.                 echo '<li><a href="'.get_permalink($postt->ID).'" title="'.$postt->post_title .'">'.$postt->post_title .'</a></li>';
  12.             ?>
  13. WordPress 教程而來。