I have implemented few search filters for custom search. So now i have search functions that gets posts by title and custom field. But the returned result is show random.
I want to have first shown search result by title, and then by custom field. Search result
Is there a way to do that?
The search works great, need just to display them by priority. Here is my code for search.
add_filter('posts_orderby','my_sort_custom',10,2);
function my_sort_custom( $orderby, $query ){
global $wpdb;
if(is_search()){
$orderby = $wpdb->prefix."posts.post_type DESC, {$wpdb->prefix}posts.ID ASC";
}
return $orderby;
}
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( like_escape( $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', 1, 2 );
function posts_join_post_meta( $join, $query ){
global $wpdb;
if( is_search()){
$join .= "
INNER JOIN
{$wpdb->postmeta} ON {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id";
}
return $join;
}
add_filter( 'posts_join', 'posts_join_post_meta', 2, 2 );
function recipe_search_where( $where, $query ){
global $wpdb;
if(is_search() ){
$where .= " OR (
{$wpdb->postmeta}.meta_key = '_recipe_incredients' AND {$wpdb->postmeta}.meta_value LIKE ('%".$wpdb->escape( get_query_var('s') )."%') ) ";
}
return $where;
}
add_filter( 'posts_where', 'recipe_search_where', 10, 2 );
最佳答案
您的帖子仅出现随机,因为您还在该行中按ID
对它们进行排序{$wpdb->prefix}posts.ID ASC
,尝试删除它并仅按帖子类型对它们进行排序。
如果上述方法不起作用,只需编写自己的纯 SQL 查询并执行即可。
另请注意:$wpdb->escape()
函数已弃用,请尝试使用 $wpdb->prepare()
以防止 SQL 注入(inject)。
仅示例:
$wpdb->query($wpdb->prepare("
SELECT $wpdb->posts
INNER JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id
WHERE 1 = 1
AND $wpdb->postmeta.meta_key = %s
AND $wpdb->postmeta.meta_value LIKE %s
ORDER BY $wpdb->posts.post_type DESC
",
'_recipe_incredients', '%'.get_query_var('s').'%')
);
参见here了解详情。
关于php - WordPress 搜索结果按优先级显示(首先按标题显示帖子),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25563214/