previous_posts_link()與next_post_lnik()這兩個函數相信各位wordpress主題開發者一定不陌生,這兩個函數是wordpress用來調用當前文章的前一篇以及后一篇文章的。但是有些時候我們為了提高網站PV提高用戶體驗想多調用幾篇文章,例如調用當前文章的前三篇文章以及后三篇文章那該怎么調用呢?查看了下wordpress的官方文檔,顯然沒有現成的代碼和函數可用。那么只好自己動手豐衣足食了。以下代碼參考自wordpress默認函數get_adjacent_post函數修改而來:
function ztmao_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;
}
將該函數放在主題的functions.php文件中即可,調用該函數的時候會返回一個數組,使用示例:
<h4>本篇教程之前的幾篇教程是</h4>
<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>
<h4>本篇教程之后的幾篇教程是</h4>
<ul>
<?php
$nextposts = ztmao_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>
新聞熱點
疑難解答