问题描述
我使用 WP_User_Query 在前端显示大量用户.
I have a large amount of users which I'm displaying on the front end with WP_User_Query
.
我在这个前端用户数据库上有一个搜索功能,并且需要能够通过自定义字段进行搜索,每个配置文件都有多个.
I have a search function on this front end user database, and need to be able to search by custom fields, which each profile has a number of.
目前搜索引擎将搜索标准 wp 用户字段,例如user_firstname"、user_lastname",但不会搜索我的自定义字段(本例中为机构"和设备"),而我不知道为什么.
Currently the search engine will search for standard wp user fields such as 'user_firstname', 'user_lastname', but won't search my custom fields ('institution' & 'equipment' in this example), and I'm not sure why.
查询:
$search = ( isset($_GET['search-meta']) ) ? sanitize_text_field($_GET['search-meta']) : false ;
if ($search){
$my_users = new WP_User_Query(
array(
'role' => 'Subscriber',
'search' => '*' . $search . '*',
'fields' => 'all',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'institution',
'value' => '*' . $search . '*',
'compare' => 'LIKE'
),
array(
'key' => 'equipment',
'value' => '*' . $search . '*',
'compare' => 'LIKE'
)
)
));
}
搜索表单:
<form method="get" id="db-search" action="<?php the_permalink() ?>">
<input type="text" class="field" name="search-meta" id="s" placeholder="Search Database" />
<button type="submit"><i class="fa fa-search"></i></button>
</form>
推荐答案
您的代码中有两个错误.
Two errors you have in your code.
- @cabrerahector 在评论中提到:您应该从
meta_query
value
中删除所有*
. 您正尝试在此处使用
搜索
:
'role' => 'Subscriber',
'search' => '*' . $search . '*',
但问题是 search
键总是会尝试从 $searchWP_User_Query#Search_Parameters" rel="nofollow noreferrer">您的 wp_users
表的电子邮件地址、URL、ID、用户名或 display_name 与关系 AND
.这意味着,如果您的 $search
与上述列之一不匹配,那么您的查询将不会返回任何内容.
But the problem is that search
key will always try to find your $search
from email address, URL, ID, username or display_name of your wp_users
table with relation AND
. This mean, that if your $search
will not match with one of the mentioned columns, then your query will return nothing.
这是从 meta_values
用户中搜索的工作代码:
Here is working code to search from meta_values
of users:
$search = ( isset($_GET['search-meta']) ) ? sanitize_text_field($_GET['search-meta']) : false ;
if ($search){
$my_users = new WP_User_Query(
array(
'role' => 'Subscriber',
'fields' => 'all',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'institution',
'value' => $search,
'compare' => 'LIKE'
),
array(
'key' => 'equipment',
'value' => $search,
'compare' => 'LIKE'
)
)
));
}
这篇关于在前端按自定义字段( user_meta )搜索用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!