萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

WordPress get_adjacent_post 函數源碼深度解析:獲取相鄰文章的核心邏輯

函數簡介

get_adjacent_post() 位於 wp-includes/link-template.php,用於取得當前文章的上一篇或下一篇發布文章,支援同分類篩選與排除特定分類。

函數簽名與參數

function get_adjacent_post(
    $in_same_cat = false,      // 是否限制同分類
    $excluded_categories = '', // 排除分類 ID(陣列或逗號字串)
    $previous = true           // true=上一篇, false=下一篇
)

回傳值三種情況

  • WP_Post 物件:成功找到相鄰文章
  • null:全域 $post 未設定
  • 空字串 '':不存在符合條件的相鄰文章

核心邏輯逐段解析

1. 前置檢查與日期取得

global $wpdb;
if ( ! $post = get_post() ) return null;
$current_post_date = $post->post_date;

使用 WordPress 資料庫抽象層 $wpdb,先確認全域文章物件存在並取得發布日期。

2. 分類篩選 SQL JOIN 建構

$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) . ")";
        }
    }
}

3. 方向與排序參數決定

$adjacent = $previous ? 'previous' : 'next';
$op       = $previous ? '<' : '>';
$order    = $previous ? 'DESC' : 'ASC';

4. 套用過濾器鉤子(可擴充點)

$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 子句,極具擴充彈性。

5. 快取機制

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 做快取鍵,命中時直接回傳文章物件,避免重複查詢。

6. 資料庫查詢與快取寫入

$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 核心的幾大設計精髓:

  • $wpdb 抽象層:資料庫操作安全與跨資料庫相容
  • 動態鉤子系統:apply_filters 讓核心邏輯可被外掛無侵入式修改
  • 物件快取:wp_cache_get/set 減輕資料庫壓力
  • 嚴謹的邊界處理:空結果、錯誤物件、相容舊版參數格式

理解此函數原理,有助於開發「相關文章」、「系列文章導航」等進階功能,並能在需要時透過鉤子精準調整查詢行為。

copyright © 萬盛學電腦網 all rights reserved