此代码应该可以正常工作,但是。。。它有一些问题。让我们将其分解并添加一些评论。
function searchcategory($query) {
if ($query->is_search) {
// Checking only for is_search is very risky. It will be set to true
// whenever param "s" is set. So your function will modify any wp_query with s,
// for instance the one in wp-admin... But also any other, even if
// the query isn\'t querying for posts...
$query->set(\'cat\',\'37\');
// You pass ID of term in here. It\'s a number. Passing it as string
// is not a problem, but it\'s another bad practice, because it will
// have to be converted to number.
}
return $query;
// It\'s an action - you don\'t have to return anything in it. Your result
// will be ignored.
}
add_filter(\'pre_get_posts\',\'searchcategory\');
// pre_get_posts is and action and not a filter.
// Due to the way actions/filters are implemented,
// you can assign your callback using `add_filter`,
// but it isn\'t a good practice.
那么如何写得更好呢?
function searchcategory($query) {
if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
$query->set( \'cat\', 37 );
}
}
add_action( \'pre_get_posts\', \'searchcategory\' );