問題描述

我正在尋找一種透過 ID 搜尋帖子的方法,最好支援自定義帖子型別。我希望有一個外掛啟用此功能,但我沒有找到任何東西。任何想法都將不勝感激,謝謝。

最佳解決方案

不知道我明白為什麼你想透過 ID 進行查詢,但是說這可能是一種駭客的方式 (我喜歡這種方法,因為它很簡單) 。

add_action( 'parse_request', 'idsearch' );
function idsearch( $wp ) {
    global $pagenow;

    // If it's not the post listing return
    if( 'edit.php' != $pagenow )
        return;

    // If it's not a search return
    if( !isset( $wp->query_vars['s'] ) )
        return;

    // If it's a search but there's no prefix, return
    if( '#' != substr( $wp->query_vars['s'], 0, 1 ) )
        return;

    // Validate the numeric value
    $id = absint( substr( $wp->query_vars['s'], 1 ) );
    if( !$id )
        return; // Return if no ID, absint returns 0 for invalid values

    // If we reach here, all criteria is fulfilled, unset search and select by ID instead
    unset( $wp->query_vars['s'] );
    $wp->query_vars['p'] = $id;
}

您所做的就是使用常規搜尋框使用數字 ID 的 #(雜湊) 字首進行搜尋。

#123

將返回一個 ID 為 123 的帖子。

我確定有更復雜的路由可以採取這樣做,但我沒有看到這種方法的任何問題,除非你有很多的帖子,標題以雜湊開頭 (但是你總是可以交換雜湊另一個角色) 。

希望有幫助。 🙂

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。