之前关于查询var的注释&hellip
WordPress使用查询变量s
将搜索的词保存到其查询中。如果正在运行自定义查询字符串,则需要修改get_search_query
过滤方式如下:/**
* Modify search query var
* Doesn\'t need to be wrapped into esc_attr(), as it\'s already done by core
*
* @param string $s | The query var to save the search in
* @return string $s
*/
function change_search_query_var( $s )
{
$s = \'your_custom_query_var\';
return $s;
}
add_filter( \'get_search_query\', \'change_search_query_var\', 20, 1 );
一些解决方案我们现在有不同的可能解决方案:简单的解决方案在模板中运行,更适合排除分类术语
A) 获取模板循环中的所有帖子,针对每个(分类)术语检查循环中的每个帖子,然后排除/不显示它。
在模板搜索中循环。php文件:
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
global $post;
// Skip if the post has the term attached
if ( is_object_in_taxonomy(
$post->ID,
\'YOUR_TAXONOMY\',
array( \'TERM A\', \'TERM B\', \'...\' )
)
continue;
}
}
这只是一个循环的例子复杂的解决方案在运行实际的主查询之前运行,更适合一般情况下排除术语
B.1) 从搜索模板查询中筛选术语。
在下面的示例中,我使用posts_clauses
过滤器,向您显示您可以仅使用一个过滤器修改更多内容(执行var_dump
的$pieces
阵列以获取更多细节)。您也可以使用posts_where
筛选器,它在子句筛选器之前运行。
// In your functions.php file
/**
* Modify the search query where clause
* Like escapes the term for security reasons
*
* @param array $pieces | The array of post clauses: Where, Group by, etc.
* @return array $pieces
*/
add_filter( \'posts_clauses\', \'alter_search_query\', 10, 2 );
function alter_search_query( $pieces, $query )
{
// Target all search queries in the front-end:
if( is_admin() || ! $query->is_search() ) return $pieces;
global $wpdb;
$term = $wpdb->esc_like( \'YOUR_TERM\' );
$pieces[\'where\'] .= $wpdb->prepare(
" AND {$wpdb->posts}.post_title NOT LIKE \'%s\'",
"%{$term}%"
);
return $pieces;
}
B.2) 以更高的性能从搜索模板查询中筛选出术语(&U);具体方式。在下面的示例中,我使用posts_search
筛选以显示如何修改where
子句仅用于搜索查询。这和posts_where
滤器
// In your functions.php file
/**
* Modify the search query where clause
* Like escapes the term for security reasons
*
* @param array $pieces | The array of post clauses: Where, Group by, etc.
* @return array $pieces
*/
add_filter( \'posts_search\', \'alter_search_where\', 10, 2 );
function alter_search_where( $search_term, $query )
{
// Target all search queries in the front-end:
if( is_admin() || ! $query->is_search() ) return $search_term;
global $wpdb;
$term = $wpdb->esc_like( \'YOUR_TERM\' );
$search_term .= $wpdb->prepare(
" AND {$wpdb->posts}.post_title NOT LIKE \'%s\'",
"%{$term}%"
);
return $search_term;
}
脚注:你还不清楚这是关于搜索还是分类学的术语