我有3个自定义帖子类型,希望搜索小部件只搜索它当前所在的自定义帖子类型。例如,如果查看cpt\\U 1(单个或存档),并且有人使用侧栏中的搜索小部件,则只应返回cpt\\U 1的结果。类似地,查看cpt\\u 2和搜索应仅返回cpt\\u 2结果。
我试过这个:
<?php
// functions.php
function search_cpt1( $query ) {
if ( $query->is_search ) {
$query->set( \'post_type\', array( \'cpt1\' ) );
}
return $query;
}
function search_cpt2( $query ) {
if ( $query->is_search ) {
$query->set( \'post_type\', array( \'cpt2\' ) );
}
return $query;
}
if ( \'cpt1\' == get_post_type() ) {
add_filter( \'pre_get_posts\', \'search_cpt1\' );
}
if ( \'cpt2\' == get_post_type() ) {
add_filter( \'pre_get_posts\', \'search_cpt2\' );
}
?>
我也尝试过这种方法,但没有成功:
<?php
function jc_search_cpts( $query ) {
if ((\'cpt1\' == get_post_type()) && ( $query->is_search )) {
$query->set( \'post_type\', array( \'cpt1\' ));
}
if ((\'cpt2\' == get_post_type()) && ( $query->is_search )) {
$query->set( \'post_type\', array( \'cpt2\' ));
}
return $query;
}
add_filter( \'pre_get_posts\', \'jc_search_cpts\' );