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

function wxd_get_post( $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 = wxd_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>
            <h4> 本篇教程之後的幾篇教程是</h4>
            <ul>
            <?php
            $nextposts = wxd_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 教程而來。