摘自Wordpress参考:
https://developer.wordpress.org/reference/hooks/posts_search/#user-contributed-notes
您可以通过以下方式仅按帖子标题进行搜索:
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);
如果您只想通过发布内容进行搜索,您可以稍微更改上述内容,然后执行以下操作:
$search .= "{$searchand}($wpdb->posts.post_content LIKE \'{$n}{$term}{$n}\')";