WooCommerce、wordpress 搜索、pre_get_posts 过滤器排除摘录和产品描述
WooCommerce, wordpress search, pre_get_posts filter exclude excerpt and product description
我正在尝试使用 pre_get_posts 挂钩修改自定义 wordpress 搜索,这样就不会在产品描述中搜索特定的词。
add_action( 'pre_get_posts', 'exclude_search_content' );
function exclude_search_content( $Q ) {
$search_phrase = $Q->query['s'];
if( $Q->is_search() ) {
/** Dont search for $search_phrase in excerpt and product description
* search only product title, a meta key and a taxonomy.
*/
}
}
似乎比我想象的要复杂。有什么想法吗?
如果你检查 posts_search reference 你会发现一些 Contribute 已经写了类似的功能,所以我只是测试它并且它工作正常。
function search_by_title_only($search, $wp_query)
{
global $wpdb;
if (empty($search)) {
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', 'search_by_title_only', 20, 2);
我正在尝试使用 pre_get_posts 挂钩修改自定义 wordpress 搜索,这样就不会在产品描述中搜索特定的词。
add_action( 'pre_get_posts', 'exclude_search_content' );
function exclude_search_content( $Q ) {
$search_phrase = $Q->query['s'];
if( $Q->is_search() ) {
/** Dont search for $search_phrase in excerpt and product description
* search only product title, a meta key and a taxonomy.
*/
}
}
似乎比我想象的要复杂。有什么想法吗?
如果你检查 posts_search reference 你会发现一些 Contribute 已经写了类似的功能,所以我只是测试它并且它工作正常。
function search_by_title_only($search, $wp_query)
{
global $wpdb;
if (empty($search)) {
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', 'search_by_title_only', 20, 2);