共计 1251 个字符,预计需要花费 4 分钟才能阅读完成。
默认状况下,在 WooCommerce 产品列表中,咱们只能通过产品题目、摘要和产品详情中蕴含的关键词来搜寻商品。在一些非凡需要下,咱们可能还须要通过产品自定义字段来搜寻产品。当然有一些插件能够实现这个需要,然而这样的插件个别都是大而全的插件,不想用插件的时候,咱们能够通过一段简略的代码来实现这个需要。
实现通过自定义字段搜寻商品的代码
在上面的代码中,咱们先是用 get_posts 函数获取蕴含指定自定义字段 (_location 和 _brand) 的文章,而后再应用获取到的文章 ID 批改 $where 数据库查问条件。
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; | |
} |
当然,实现下面的性能比默认的搜寻会减少一个数据库查问,必定会对性能带来一些影响,如果不是必须,不倡议是用下面的办法来实现商品查问。对于一些常常须要搜寻的字段,咱们能够整顿一下,创立一个自定义分类办法来分类查问,这是一种对性能影响比拟小的解决方法。
正文完