仅在帖子标题中进行 WordPress 搜索
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9468804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make WordPress search only in post title
提问by Rania York
I have a new website and I want to modify WordPress Mystique theme 3.0 in order to search only in post title.
我有一个新网站,我想修改 WordPress Mystique 主题 3.0,以便仅在帖子标题中进行搜索。
How can I do it?
我该怎么做?
回答by Rizwan Mumtaz
There are numbers of articles available in Google if you have searched before you posted.
WordPress search only in post title
如果您在发布之前进行了搜索,那么在 Google 中可以找到大量文章。
WordPress 仅在帖子标题中搜索
function __search_by_title_only( $search, &$wp_query )
{
global $wpdb;
if(empty($search)) {
return $search; // skip processing - no search term in query
}
$q = $wp_query->query_vars;
$n = !empty($q['exact']) ? '' : '%';
$search =
$searchand = '';
foreach ((array)$q['search_terms'] as $term) {
$term = esc_sql($wpdb->esc_like($term));
$search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
$searchand = ' AND ';
}
if (!empty($search)) {
$search = " AND ({$search}) ";
if (!is_user_logged_in())
$search .= " AND ($wpdb->posts.post_password = '') ";
}
return $search;
}
add_filter('posts_search', '__search_by_title_only', 500, 2);
Add this code to your functions.php
将此代码添加到您的functions.php