本站中的教程都是成系列的文章,所以為了提高使用者體驗,我在每篇教程的後面列出當前文章的前 3 篇文章和後 3 篇文章,這個可以當成是相關文章吧。
程式碼乃是我參考 wp 自帶的 get_adjacent_post 函式修改而來,get_adjacent_post 函式是 WordPress 用來獲取上一篇和下一篇文章的基本函式。哎呀文采不好就不廢話了函式程式碼:
函式作用:獲取當前文章同分類下的前幾篇文章和後幾篇文章
引數:$previous 為 true 時獲取之前的文章, 為 false 的時候獲取之後的文章
$number 為獲取文章數量
- //author:www.ashuwp.com
- function ashu_get_adjacent_posts( $previous = true, $number = 1 ) {
- //global 當前文章變數 $post 和資料庫操作類 wpdb
- global $post, $wpdb;
- if ( empty( $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;
- }
將該函式放在主題的 functions.php 檔案中即可,呼叫該函式的時候會返回一個陣列,使用示例:
- <h4> 本篇教程之前的幾篇教程是</h4>
- <ul>
- <?php
- $preposts = ashu_get_adjacent_posts(true,3);
- foreach( $preposts as $postt ){
- echo '<li><a href="'.get_permalink($postt->ID).'" title="'.$postt->post_title .'">'.$postt->post_title .'</a></li>';
- };
- ?>
- </ul>
- <h4> 本篇教程之後的幾篇教程是</h4>
- <ul>
- <?php
- $nextposts = ashu_get_adjacent_posts(false,3);
- foreach( $nextposts as $postt ){
- echo '<li><a href="'.get_permalink($postt->ID).'" title="'.$postt->post_title .'">'.$postt->post_title .'</a></li>';
- };
- ?>
- </ul>
效果預覽:
