previous_posts_link()與next_post_lnik()這兩個函數(shù)相信各位wordpress主題開發(fā)者一定不陌生,這兩個函數(shù)是wordpress用來調(diào)用當(dāng)前文章的前一篇以及后一篇文章的。但是有些時候我們?yōu)榱颂岣呔W(wǎng)站PV提高用戶體驗想多調(diào)用幾篇文章,例如調(diào)用當(dāng)前文章的前三篇文章以及后三篇文章那該怎么調(diào)用呢?魔客吧查看了下wordpress的官方文檔,顯然沒有現(xiàn)成的代碼和函數(shù)可用。那么只好自己動手豐衣足食了。以下代碼參考自wordpress默認函數(shù)get_adjacent_post函數(shù)修改而來:
function v7v3_get_post( $previous = true, $number = 1 ) { //global當(dāng)前文章變量 $post 和數(shù)據(jù)庫操作類wpdb global $post, $wpdb; if ( empty( $post ) ) return null; $current_post_date = $post->post_date;//當(dāng)前文章的時間 $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"; //獲取當(dāng)前文章所屬分類,可以同屬多個分類,如果是自定義的分類法,將category換成對應(yīng)的分類法即可 $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; }
將該函數(shù)放在主題的functions.php文件中即可,調(diào)用該函數(shù)的時候會返回一個數(shù)組,使用示例:
本篇教程之前的幾篇教程是ID).'" title="'.$postt->post_title .'">'.$postt->post_title .''; }; ?>本篇教程之后的幾篇教程是ID).'" title="'.$postt->post_title .'">'.$postt->post_title .''; }; ?>
版權(quán)聲明: 本站資源均來自互聯(lián)網(wǎng)或會員發(fā)布,如果侵犯了您的權(quán)益請與我們聯(lián)系,我們將在24小時內(nèi)刪除!謝謝!
轉(zhuǎn)載請注明: wordpress開發(fā)教程:獲取當(dāng)前文章的前幾篇以及后幾篇文章