![](/img/trans.png)
[英]How to create an AJAX Custom Post Type Archive Page with search on Wordpress
[英]Wordpress add search to custom post type archive
我有一个包含许多自定义帖子类型的网站,例如players
teams
......
对于他们中的每一个,我都有存档页面,例如: player-archive.php
在自定义帖子类型存档页面中,我想在顶部添加一个搜索(如果可能,并过滤)。
PS:我看到其他关于搜索的代码的问题,但它不起作用,并且没有问题的答案和其他带有插件的问题,但它们通常可以改进站点中的所有搜索。
所以首先,如果有任何关于插件的建议也可能会很棒。
您只需 3 步即可轻松完成
假设您的自定义帖子类型是“玩家”
1 . 添加功能代码
在这里你可以指定archive-search.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 . 为自定义帖子类型创建搜索结果模板( search-archive.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>
这三个步骤对我有用:
第 1 步:创建用于搜索的表单
第 2 步:在您的 function.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 步:创建一个 search.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://wpsnipp.com/index.php/template/create-multiple-search-templates-for-custom-post-types/
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.