WooCommerce 允许在仪表盘中通过自定义字段搜索商品

默认情况下,在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;
}

当然,实现上面的功能比默认的搜索会增加一个数据库查询,肯定会对性能带来一些影响,如果不是必需,不建议是用上面的方法来实现商品查询。对于一些经常需要搜索的字段,我们可以整理一下,创建一个自定义分类方法来分类查询,这是一种对性能影响比较小的处理办法。

你可能感兴趣的:(WooCommerce 允许在仪表盘中通过自定义字段搜索商品)