默認(rèn)情況下,在WooCommerce 產(chǎn)品列表中,我們只能通過(guò)產(chǎn)品標(biāo)題、摘要和產(chǎn)品詳情中包含的關(guān)鍵詞來(lái)搜索商品。在一些特殊需求下,我們可能還需要通過(guò)產(chǎn)品自定義字段來(lái)搜索產(chǎn)品。當(dāng)然有一些插件可以實(shí)現(xiàn)這個(gè)需求,但是這樣的插件一般都是大而全的插件,用的多了,會(huì)不可避免的拖慢網(wǎng)站速度,在不想用插件的時(shí)候,我們可以通過(guò)一段簡(jiǎn)單的代碼來(lái)實(shí)現(xiàn)這個(gè)需求。
實(shí)現(xiàn)通過(guò)自定義字段搜索商品的代碼
在下面的代碼中,我們先是用 get_posts 函數(shù)獲取包含指定自定義字段(_location 和 _brand)的文章,然后再使用獲取到的文章 ID 修改 $where 數(shù)據(jù)庫(kù)查詢條件。
add_filter('posts_where', 'wprs_search_products_by_custom_field_in_admin', 9999, 2);
function wprs_search_products_by_custom_field_in_admin($where, $wp_query)
{
global $wpdb, $pagenow;
$post_type = 'product';
$custom_fields = [
"_location",
"_brand",
];
if (is_admin() && 'edit.php' === $pagenow && $wp_query->query[ 'post_type' ] === $post_type && isset($_GET[ 's' ])) {
$get_post_ids = [];
foreach ($custom_fields as $custom_field_name) {
$args = [
'posts_per_page' => -1,
'post_type' => $post_type,
'meta_query' => [
[
'key' => $custom_field_name,
'value' => wc_clean(wp_unslash($_GET[ 's' ])),
'compare' => 'LIKE',
],
],
'fields' => 'ids',
];
$posts = get_posts($args);
if ( ! empty($posts)) {
foreach ($posts as $post_id) {
$get_post_ids[] = $post_id;
}
}
}
$search_ids = array_filter(array_unique(array_map('absint', $get_post_ids)));
if (count($search_ids) > 0) {
$where = str_replace("wp_posts.ID IN (0)", "wp_posts.ID IN (" . implode(',', $search_ids) . ")", $where);
}
}
return $where;
}
當(dāng)然,實(shí)現(xiàn)上面的功能比默認(rèn)的搜索會(huì)增加一個(gè)數(shù)據(jù)庫(kù)查詢,肯定會(huì)對(duì)性能帶來(lái)一些影響,如果不是必需,不建議是用上面的方法來(lái)實(shí)現(xiàn)商品查詢。對(duì)于一些經(jīng)常需要搜索的字段,我們可以整理一下,創(chuàng)建一個(gè)自定義分類(lèi)方法來(lái)分類(lèi)查詢,這是一種對(duì)性能影響比較小的處理辦法。
如果您想在WordPress前端搜索功能中實(shí)現(xiàn)本文中的類(lèi)似功能,可以參考本站之前的文章:WordPress 根據(jù)自定義字段搜索文章內(nèi)容


