問題描述
我有一個搜尋欄位的部落格帖子,但我需要一個其他的自定義帖子型別。如何建立具有不同搜尋結果佈局的自定義搜尋表單?
最佳解決方案
這是我試過的,並得到一個解決方案 3 步。假設您的自定義帖子型別是”products”
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 == 'products' )
{
return locate_template('archive-search.php'); // redirect to archive-search.php
}
return $template;
}
add_filter('template_include', 'template_chooser');
2 。建立自定義帖子型別的搜尋結果模板 (search-archive.php)
<?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="http://<?php%20the_permalink();%20?>" title="<?php the_title(); ?>"><?php the_title(); ?></a><h4>
<p><?php the_exerpt(); ?></p>
<p align="right"><a href="http://<?php%20the_permalink();%20?>">Read More</a></p>
<span class="post-meta"> Post By <?php the_author(); ?>
| Date : <?php echo date('j F Y'); ?></span>
</article><!-- #post -->
</div>
<?php endwhile; ?>
<?php endif; ?>
</div><!-- content -->
</div><!-- contentarea -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
-
構建搜尋表單在此搜尋表單中,值”products” 被隱藏,它將僅搜尋產品帖子。
<div> <h3>Search Products</h3> <form role="search" action="<?php echo site_url('/'); ?>" method="get" id="searchform"> <input type="text" name="s" placeholder="Search Products"/> <input type="hidden" name="post_type" value="products" /> <!-- // hidden 'products' value --> <input type="submit" alt="Search" value="Search" /> </form> </div>
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。