以下是对我有效的方法。没有那么干净,但我无法得到任何其他答案。
Search form for Custom Post Type:
<form role="search" method="get" class="search-form" action="<?php echo home_url( \'/\' ); ?>">
<label>
<span class="screen-reader-text"><?php echo _x( \'Search for:\', \'label\' ) ?></span>
<input type="search" class="search-field" placeholder="<?php echo esc_attr_x( \'Search …\', \'placeholder\' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( \'Search for:\', \'label\' ) ?>" />
<input type="hidden" name="post_type" value="book" />
</label>
<input type="submit" class="search-submit" value="<?php echo esc_attr_x( \'Search\', \'submit button\' ) ?>" />
</form>
In functions.php:
function searchfilter($query) {
if ($query->is_search && !is_admin() ) {
if(isset($_GET[\'post_type\'])) {
$type = $_GET[\'post_type\'];
if($type == \'book\') {
$query->set(\'post_type\',array(\'book\'));
}
}
}
return $query;
}
add_filter(\'pre_get_posts\',\'searchfilter\');
In search.php:
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<?php if(isset($_GET[\'post_type\'])) {
$type = $_GET[\'post_type\'];
if($type == \'book\') {?>
/* Format for "book" custom post type */
<?php } else { ?>
/* Format for custom post types that are not "book,"
or you can use elseif to specify a second post type the
same way as above. Copy the default format here if you
only have one custom post type. */
<?php } ?>
<?php } else { ?>
/* Format to display when the post_type parameter
is not set (i.e. default format) */
<?php } ?>
<?php endwhile; else: ?>
/* What to display if there are no results. */
<?php endif; ?>
当然,在这三个地方,你都需要用你的自定义帖子类型来替换“book”。
希望这对别人有帮助!