我试图使用他们在WooCommerce产品搜索中启用自定义分类时的回答中提供的解决方案@LoicTheAztec
function search_product_by_tag( $search, &$query_vars ) {
global $wpdb, $pagenow;
if ( 'edit.php' == $pagenow || empty($search) ) {
return $search;
}
$args = array(
'posts_per_page' => -1,
'post_type' => 'product',
'meta_query' => array(
array(
'key' => 'taxonomy',
'value' => 'product_tag',
'field' => 'name',
'terms' => array($query_vars->query['s']),
'compare' => 'LIKE',
)));
$posts = get_posts( $args );
if ( empty( $posts ) ) return $search;
$get_post_ids = array();
foreach($posts as $post){
$get_post_ids[] = $post->ID;
}
if ( sizeof( $get_post_ids ) > 0 ) {
$search = str_replace( 'AND (((', "AND ((({$wpdb->posts}.ID IN (" . implode( ',', $get_post_ids ) . ")) OR (", $search);
}
return $search;
}
add_filter( 'posts_search', 'search_product_by_tag', 999, 2 );
但是,将上述片段添加到functions.php在前端不起作用,用户无法通过product_tag成功搜索。
我已经在使用下面的代码,使用单独的代码片段将搜索范围缩小到只搜索产品和SKU。
function search_by_sku( $search, &$query_vars ) {
global $wpdb;
if(isset($query_vars->query['s']) && !empty($query_vars->query['s'])){
$args = array(
'posts_per_page' => -1,
'post_type' => 'product',
'meta_query' => array(
array(
'key' => '_sku',
'value' => $query_vars->query['s'],
'compare' => 'LIKE'
)
)
);
$posts = get_posts($args);
if(empty($posts)) return $search;
$get_post_ids = array();
foreach($posts as $post){
$get_post_ids[] = $post->ID;
}
if(sizeof( $get_post_ids ) > 0 ) {
$search = str_replace( 'AND (((', "AND ((({$wpdb->posts}.ID IN (" . implode( ',', $get_post_ids ) . ")) OR (", $search);
}
}
return $search;
}
add_filter( 'posts_search', 'search_by_sku', 999, 2 );
function searchfilter($query) {
if ($query->is_search && !is_admin() ) {
$query->set('post_type',array('product'));
$query->set('posts_per_page',12);
}
return $query;
}
add_filter('pre_get_posts','searchfilter');
这些可能会引起冲突吗?
我看到你的代码有以下信息
'posts_per_page' => -1,
另一行上还有以下代码:
if ( sizeof( $get_post_ids ) > 0 ) {
这个也查一下
请检查此数据,然后重试。。。
启用调试和发布错误日志,确定吗
str_替换('和(',)和(({$wpdb-
这里一定有一些'或"失踪。