我在wordpress网站上使用自定义的woocommerce产品搜索,只搜索产品标题。我也想在类别名称中包含搜索。因此,如果有人搜索文本,并且产品类别名称中存在该文本,则还需要列出该类别下的所有产品。
以下是我正在使用的代码:
function wc_filter_search_by_title_only( $search, &$wp_query ) {
global $wpdb;
$not_allowed_post_types = apply_filters( 'wc_filter_search_not_allowed_array', array(
'product', //Default WooCommerce products post type
'shop_webhook', //MyStyle Custom post type
) );
if ( empty( $search ) || ! in_array( $wp_query->query_vars['post_type'], $not_allowed_post_types ) ) {
return $search; // skip processing - no search term in query
}
$q = $wp_query->query_vars;
$n = ! empty( $q['exact'] ) ? '' : '%';
$search =
$searchand = '';
foreach ( (array) $q['search_terms'] as $term ) {
$term = esc_sql( $wpdb->esc_like( $term ) );
$search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
$searchand = ' AND ';
}
if ( ! empty( $search ) ) {
$search = " AND ({$search}) ";
if ( ! is_user_logged_in() )
$search .= " AND ($wpdb->posts.post_password = '') ";
}
return $search;
}
add_filter( 'posts_search', 'wc_filter_search_by_title_only', 500, 2 );
请告诉我,无论如何我都可以实现这一点。
提前谢谢。