如何在WooCommerce订单列表注册客户筛选AJAX搜索中加入自定义用户元
如何让WooCommerce订单列表的客户AJAX搜索包含自定义用户元字段
别担心,不用直接修改WC_AJAX::json_search_customers核心函数——WooCommerce提供了现成的过滤器让我们轻松扩展这个功能,完全符合WordPress的开发规范。下面分两步来实现你的需求:
1. 修改AJAX搜索查询,加入自定义字段匹配
我们可以通过woocommerce_json_search_customers_query过滤器,把sageaccountnumber字段加入到搜索的匹配条件中,同时保留原有的搜索逻辑(用户名、邮箱、姓名):
/** * 扩展WooCommerce客户AJAX搜索,支持匹配sageaccountnumber自定义字段 */ add_filter( 'woocommerce_json_search_customers_query', 'sab_extend_customer_search_with_sage_account', 10, 2 ); function sab_extend_customer_search_with_sage_account( $query_args, $term ) { // 构建元查询,同时匹配默认字段和自定义字段 $query_args['meta_query'] = array( 'relation' => 'OR', // 保留默认的姓名搜索 array( 'key' => 'first_name', 'value' => $term, 'compare' => 'LIKE', ), array( 'key' => 'last_name', 'value' => $term, 'compare' => 'LIKE', ), // 新增sageaccountnumber字段的搜索 array( 'key' => 'sageaccountnumber', 'value' => $term, 'compare' => 'LIKE', ), ); // 保留默认的用户名、邮箱搜索逻辑 $query_args['search'] = sprintf( '*%s*', esc_sql( $term ) ); $query_args['search_columns'] = array( 'user_login', 'user_email' ); return $query_args; }
2. (可选)在搜索结果中显示Sage账号
如果希望在搜索下拉列表里直接看到用户对应的Sage账号,方便快速识别,可以用woocommerce_json_search_found_customer过滤器修改结果的显示文本:
/** * 在客户AJAX搜索结果中追加显示Sage账号 */ add_filter( 'woocommerce_json_search_found_customer', 'sab_display_sage_account_in_search_results', 10, 2 ); function sab_display_sage_account_in_search_results( $display_name, $user ) { $sage_account = get_user_meta( $user->ID, 'sageaccountnumber', true ); if ( ! empty( $sage_account ) ) { $display_name .= ' (Sage账号: ' . esc_html( $sage_account ) . ')'; } return $display_name; }
使用方法
把上面的代码添加到你的WordPress主题的functions.php文件中,或者创建一个自定义插件来存放这些代码。之后刷新订单列表页面,在「按注册客户筛选」的输入框中输入Sage账号,就能匹配到对应的用户了。
内容的提问来源于stack exchange,提问作者DSmit
相关产品推荐
相关产品推荐

