我想同时在 Woocommerce 中搜索多个产品。因此,我不想逐一搜索,而是输入以逗号或类似内容分隔的产品列表。
我发现 Bjorn 的这段代码可以同时搜索多个 SKU,但我想按产品名称进行搜索。这可能吗?
/**
* Use multiple sku's to find WOO products in wp-admin
* NOTE: Use '|' as a sku delimiter in your search query. Example: '1234|1235|1236'
**/
function woo_multiple_sku_search( $query_vars ) {
global $typenow;
global $wpdb;
global $pagenow;
if ( 'product' === $typenow && isset( $_GET['s'] ) && 'edit.php' === $pagenow ) {
$search_term = esc_sql( sanitize_text_field( $_GET['s'] ) );
if (strpos($search_term, '|') == false) return $query_vars;
$skus = explode('|',$search_term);
$meta_query = array(
'relation' => 'OR'
);
if(is_array($skus) && $skus) {
foreach($skus as $sku) {
$meta_query[] = array(
'key' => '_sku',
'value' => $sku,
'compare' => '='
);
}
}
$args = array(
'posts_per_page' => -1,
'post_type' => 'product',
'meta_query' => $meta_query
);
$posts = get_posts( $args );
if ( ! $posts ) return $query_vars;
foreach($posts as $post){
$query_vars['post__in'][] = $post->ID;
}
}
return $query_vars;
}
add_filter( 'request', 'woo_multiple_sku_search', 20 );
要按产品名称而不是产品 SKU 进行搜索,您可以使用自定义 SQL 查询并搜索
post_title
(WooCommerce 产品是自定义帖子类型)。
此外,您不必单独声明多个全局变量,您可以通过用“逗号”分隔将它们全部写入一个实例中。 (这并没有什么最大的区别)。
要按
,
(逗号)而不是 |
或任何您想要的符号/分隔符进行搜索,您只需更改这两行代码中的指示符(例如 '|'
或 ','
或 '+'
):
if (strpos($search_term, ',') === false) return $query_vars;
$terms = explode(',', $search_term);
将现有代码替换为以下代码:
/*Search multiple product names in WOO products in wp-admin*/
function woo_multiple_name_search( $query_vars ) {
global $typenow, $pagenow, $wpdb; // Declaring global variables
// Check if we are in the admin area, on the product edit page, and a search is being performed
if ( is_admin() && 'product' === $typenow && isset( $_GET['s'] ) && 'edit.php' === $pagenow ) {
$search_term = esc_sql( sanitize_text_field( $_GET['s'] ) );
// Check if the search term contains ',' indicating multiple search terms
if (strpos($search_term, ',') === false) return $query_vars;
$terms = explode(',', $search_term); // Split the search terms by ',' comma
$post_ids = array(); // Initialize an array to hold the post IDs
// Loop through each element in $terms array
foreach ($terms as $term) {
// Custom SQL query to search by product name
$name_query = $wpdb->get_results($wpdb->prepare("
SELECT ID FROM {$wpdb->posts}
WHERE post_type = 'product'
AND post_title LIKE %s
", '%' . $wpdb->esc_like($term) . '%'));
// If there are results, add the post IDs to the array
if ($name_query) {
foreach ($name_query as $post) {
$post_ids[] = $post->ID;
}
}
}
// If no posts are found, return the original query vars
if ( ! $post_ids ) return $query_vars;
// Set the post__in parameter to the array of post IDs
$query_vars['post__in'] = $post_ids;
}
return $query_vars;
}
add_filter( 'request', 'woo_multiple_name_search', 20 );
添加到您的
active子主题的
functions.php
文件中。经过测试并在我这边工作。