get_adjacent_post() 位於 wp-includes/link-template.php,用於取得當前文章的上一篇或下一篇發布文章,支援同分類篩選與排除特定分類。
function get_adjacent_post(
$in_same_cat = false, // 是否限制同分類
$excluded_categories = '', // 排除分類 ID(陣列或逗號字串)
$previous = true // true=上一篇, false=下一篇
)
$post 未設定global $wpdb;
if ( ! $post = get_post() ) return null;
$current_post_date = $post->post_date;
使用 WordPress 資料庫抽象層 $wpdb,先確認全域文章物件存在並取得發布日期。
$join = '';
$posts_in_ex_cats_sql = '';
if ( $in_same_cat || ! empty( $excluded_categories ) ) {
// 關聯 term_relationships 與 term_taxonomy 表
$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";
if ( $in_same_cat ) {
// 確認文章類型支援 category 分類法
if ( ! is_object_in_taxonomy( $post->post_type, 'category' ) ) return '';
// 取得當前文章的分類 ID 陣列
$cat_array = wp_get_object_terms($post->ID, 'category', ['fields' => 'ids']);
if ( ! $cat_array || is_wp_error( $cat_array ) ) return '';
// 限制同分類
$join .= " AND tt.taxonomy = 'category' AND tt.term_id IN (" . implode(',', $cat_array) . ")";
}
$posts_in_ex_cats_sql = "AND tt.taxonomy = 'category'";
// 處理排除分類
if ( ! empty( $excluded_categories ) ) {
// 相容舊版 "and" 分隔符
if ( ! is_array( $excluded_categories ) ) {
if ( strpos( $excluded_categories, ' and ' ) !== false ) {
_deprecated_argument( __FUNCTION__, '3.3', ... );
$excluded_categories = explode( ' and ', $excluded_categories );
} else {
$excluded_categories = explode( ',', $excluded_categories );
}
}
$excluded_categories = array_map( 'intval', $excluded_categories );
// 排除當前文章已屬分類(避免自我排除導致無結果)
if ( ! empty( $cat_array ) ) {
$excluded_categories = array_diff($excluded_categories, $cat_array);
if ( empty($excluded_categories) ) $posts_in_ex_cats_sql = '';
}
if ( ! empty($excluded_categories) ) {
$posts_in_ex_cats_sql = " AND tt.taxonomy = 'category'
AND tt.term_id NOT IN (" . implode(',', $excluded_categories) . ")";
}
}
}
$adjacent = $previous ? 'previous' : 'next';
$op = $previous ? '<' : '>';
$order = $previous ? 'DESC' : 'ASC';
$join = apply_filters( "get_{$adjacent}_post_join", $join, $in_same_cat, $excluded_categories );
$where = apply_filters( "get_{$adjacent}_post_where", $wpdb->prepare(
"WHERE p.post_date $op %s AND p.post_type = %s AND p.post_status = 'publish' $posts_in_ex_cats_sql",
$current_post_date, $post->post_type
), $in_same_cat, $excluded_categories );
$sort = apply_filters( "get_{$adjacent}_post_sort", "ORDER BY p.post_date $order LIMIT 1" );
三個動態鉤子允許外掛修改 JOIN、WHERE、ORDER BY 子句,極具擴充彈性。
posts AS p $join $where $sort";
$query_key = 'adjacent_post_' . md5($query);
$result = wp_cache_get($query_key, 'counts');
if ( false !== $result ) {
if ( $result ) $result = get_post( $result );
return $result;
}
以完整 SQL 為 Key 的 MD5 做快取鍵,命中時直接回傳文章物件,避免重複查詢。
$result = $wpdb->get_var( $query );
if ( null === $result ) $result = '';
wp_cache_set($query_key, $result, 'counts');
if ( $result ) $result = get_post( $result );
return $result;
get_var 只取單一欄位(文章 ID),再透過 get_post() 載入完整物件。
SELECT p.id
FROM wp_posts AS p
INNER JOIN wp_term_relationships AS tr ON p.ID = tr.object_id
INNER JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
WHERE p.post_date < '2024-01-15 10:30:00'
AND p.post_type = 'post'
AND p.post_status = 'publish'
AND tt.taxonomy = 'category'
AND tt.term_id IN (3,7,12)
AND tt.term_id NOT IN (99)
ORDER BY p.post_date DESC LIMIT 1
<?php
// 在 functions.php 中修改排除邏輯
add_filter( 'get_previous_post_where', function( $where, $in_same_cat, $excluded_categories ) {
// 額外排除標記為 "private" 的分類
global $wpdb;
$private_cats = get_terms(['taxonomy' => 'category', 'meta_query' => [['key' => '_private', 'value' => '1']]]);
if ( $private_cats ) {
$ids = implode(',', wp_list_pluck($private_cats, 'term_id'));
$where .= " AND tt.term_id NOT IN ($ids)";
}
return $where;
}, 10, 3 );
get_adjacent_post() 展現 WordPress 核心的幾大設計精髓:
理解此函數原理,有助於開發「相關文章」、「系列文章導航」等進階功能,並能在需要時透過鉤子精準調整查詢行為。