問題描述
我有一個 CPT 設置與附加的自定義分類法。我最近注意到,如果我搜索 0(零),在 back-end 以及 front-end,它給我的結果。這些結果的帖子中沒有一個在標題和內容的任何地方都有 0 。反正我沒有修改循環,只是簡單的搜索模板。這讓我想知道 2 件事情:
-
WP 默認搜索是什麼?
-
有沒有辦法阻止它搜索
0?
有任何想法嗎?
更新:
從以下評論中我更新了我的要求:
當輸入 0 作為搜索鍵時,是否有辦法在標題或內容中搜索包含 0 的帖子?
最佳解決方案
考慮 @Mayeenul 伊斯蘭教評論:
I’ve just tested in a blank theme with dummy data, search with 0 (zero) fired an empty search – that means all:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type IN ('post', 'page', 'attachment') AND (wp_posts.post_status = 'publish') ORDER BY wp_posts.post_date DESC LIMIT 0, 10
和 wp-includes/query.php 包含的事實
if ( ! empty( $q['s'] ) ) {
$search = $this->parse_search( $q );
}
,我們可以看到!empty($q['s']),其中 $q['s'] == 0 (or "0")將返回 FALSE 。這意味着搜索查詢不會有 LIKE 部分,當 $q['s'] == 0 和它返回”all” 的帖子,因為沒有限制查詢具體條件,應該在 LIKE 內部。
這是由 empty()功能文檔證實的:
The following things are considered to be empty:
…
- 0 (0 as an integer)
- “0” (0 as a string)
…
由於我們無法過濾/更新,”0″ 為了通過 if-empty 條件邏輯。我建議的是查詢更新,以防用户要搜索”0″ 。
這是一個 quickfix 如何讓用户搜索”0″ 。
add_filter("posts_where", "search_hotfix", 10, 1);
function search_hotfix($where_clause){
if(get_query_var('s') == 0){
$where_clause .= " AND (((wp_posts.post_title LIKE '%0%') OR (wp_posts.post_content LIKE '%0%'))) ";
}
return $where_clause;
}
更新:
這裏是一個 quickfix 如何停止 WP 搜索”0″ 。此代碼將強制 WP_Query 不提供任何結果。
add_action('pre_get_posts', 'search_hotfix_reset_q');
function search_hotfix_reset_q($query){
if ( get_query_var('s') == 0) {
$query->query_vars['post__in'] = array(0);
}
}
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。