>我有一个有很多自定义帖子类型的网站例如players
teams
...
对于他们中的每一个,我都有存档页面,例如:player-archive.php
自定义帖子类型存档页面中,我想在顶部添加搜索(如果可能的话,请过滤)。
PS :我看到其他问题带有有关搜索的代码,但它不起作用,并且没有问题的答案和其他带有插件的问题,但它们是通用的,可以改善网站中的所有搜索。
所以首先,如果有任何关于插件的建议,也有可能很棒.
您有 3 个简单的步骤
假设您的自定义帖子类型是"玩家"
1 .添加功能代码
您可以在此处指定存档搜索.php
function template_chooser( $template ){
global $wp_query;
$post_type = get_query_var('post_type');
if( $wp_query->is_search && $post_type == 'players' ){
return locate_template('archive-search.php'); // redirect to archive-search.php
}
return $template;
}
add_filter( 'template_include', 'template_chooser' );
2 . 为自定义帖子类型创建搜索结果模板(搜索存档.php )
/* Template Name: Custom Search */
get_header(); ?>
<div class="contentarea">
<div id="content" class="content_right">
<h3>Search Result for : <?php echo "$s"; ?> </h3>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" class="posts">
<article>
<h4><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a><h4>
<p><?php the_exerpt(); ?></p>
<p align="right"><a href="<?php the_permalink(); ?>">Read More</a></p>
<span class="post-meta"> Post By <?php the_author(); ?>
| Date : <?php echo date('j F Y'); ?></span>
</article>
</div>
<?php endwhile; ?>
<?php endif; ?>
</div><!-- content -->
</div><!-- contentarea -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
3 .构建搜索表单
在此搜索表单中,值"玩家"是隐藏的,它将仅搜索玩家帖子。
<div>
<h3>Search players</h3>
<form role="search" action="<?php echo site_url('/'); ?>" method="get" id="searchform">
<input type="text" name="s" placeholder="Search players"/>
<input type="hidden" name="post_type" value="players" /> <!-- // hidden 'players' value -->
<input type="submit" alt="Search" value="Search" />
</form>
</div>
这 3 个步骤对我有用:
步骤 1:创建用于搜索的表单
第 2 步:在您的函数中.php添加以下代码:
function searchfilter($query) {
if ($query->is_search && !is_admin() ) {
if(isset($_GET['post_type'])) {
$type = $_GET['post_type'];
if($type == 'product') {
$query->set('post_type',array('product'));
}
}
}
return $query;
}
add_filter('pre_get_posts','searchfilter');
第 3 步:创建搜索.php文件广告添加:
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<?php if(isset($_GET['post_type'])) {
$type = $_GET['post_type'];
if($type == 'product') {?>
/* Format for "product" custom post type */
<?php }?>
<?php } else { ?>
<?php } ?>
<?php endwhile; else: ?>
<?php endif; ?>
供您参考:
http://www.wpbeginner.com/wp-tutorials/how-to-create-advanced-search-form-in-wordpress-for-custom-post-types/
http://wpsnipp.com/index.php/template/create-multiple-search-templates-for-custom-post-types/
希望这有帮助!