WordPress搜索功能只能完成基本的搜索,如果我希望對搜索結果進行一些操作就不能實現了,下面我找到一博客中寫到可以對搜索進行如 顯示標題數 高亮搜索文本等功能.
默認的搜索結果中是不會顯示結果文章數的,可能對一些人來說會需要這個結果數,要在搜索結果中顯示文章數,很簡單,你只需要編輯search.php,找到如下代碼:
<h1>Search Results</h1> 替換為如下代碼內容:
- <h1><?php
- /* Search Count */
- $allsearch = &new WP_Query("s=$s&showposts=-1");
- $key = wp_specialchars($s, 1);
- $count = $allsearch->post_count; _e('');
- _e('<span>');
- echo $key; _e('</span>的搜索結果'); _e(' — ');
- echo $count . ' '; _e('篇文章');
- wp_reset_query(); ?></h1>
關于搜索結果中顯示數目的demo,可以看看本博客的搜索頁面,雖然不一樣但基本上差不多,在搜索列表文章標題中高亮搜索文本,高亮搜索文文能夠使搜索者準確的看到想要知道的內容,依然編輯search.php,找到你的文章輸出loop,代碼如下:
- <h2><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>" rel="bookmark">
- <?php the_title(); ?>
- </a></h2>
替換為:
- <?php
- $title = get_the_title();
- $keys= explode(" ",$s);
- $title = preg_replace('/('.implode('|', $keys) .')/iu',
- '<strong></strong>',
- $title);
- ?>
- <h2><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>" rel="bookmark">
- <?php echo $title; ?>
- </a></h2>
然后在你的css中加入下面的樣式:strong.search-excerpt {background:blue;},當搜索結果只有一篇時直接重定向到該文章,用下面的方法可以很方便的實現當搜索結果只有一篇時直接重定向到該文章,編輯你的functions.php并加入以下代碼:
- add_action('template_redirect', 'redirect_single_post');
- function redirect_single_post() {
- if (is_search()) {
- global $wp_query;
- if ($wp_query->post_count == 1) {
- wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
- }
- }
- }
demo可以看水煮魚的博客,他那個就是自動跳轉的
更改Wordpress搜索結果每頁顯示文章數
WordPress默認的搜索結果是每頁顯示十篇文章,如果你想更改的話,只需要把下面的代碼加到functions.php中并修改數量.代碼如下:
- function limit_posts_per_search_page() {
- if ( is_search() )
- set_query_var('posts_per_archive_page', 20);
- }
- add_filter('pre_get_posts', 'limit_posts_per_search_page');
搜索結果限制文章格式
如果你的主題支持多種文章格式并且你想在搜索結果中只輸出一種格式,你只需要把下面的代碼放到functions.php,并修改你想要顯示的文章格式名稱,代碼如下:
- function SearchFilter($query) {
- if ($query->is_search) {
- // 輸入你想要顯示的文章格式
- $query->set('post_type', 'feeds');
- }
- return $query;
- }
- add_filter('pre_get_posts','SearchFilter');
只搜索指定分類:
做到這個很簡單,只需要修改下面代碼的分類ID號并加入到search.php中,代碼如下:
- <?php if( is_search() ) :
- $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
- query_posts("s=$s&paged=$paged&cat=1,2,3");//cat的值就是分類的ID
- endif; ?>
完全禁用搜索功能
雖然搜索是個很有用的功能,但是有時候強迫癥的你就是想禁用它,那么你只需要把下面的代碼放到functions.php中:
- function fb_filter_query( $query, $error = true ) {
- if ( is_search() ) {
- $query->is_search = false;
- $query->query_vars[s] = false;
- $query->query[s] = false;
- // to error
- if ( $error == true )
- $query->is_404 = true;
- }
- }
- add_action( 'parse_query', 'fb_filter_query' );
- add_filter( 'get_search_form', create_function( '$a', "return null;" ) );
在一頁中顯示所有搜索結果
前面已經提到,默認搜索結果每頁顯示10篇,如果你想讓結果在一頁里顯示,只需要編輯search.php,找到下面的代碼:
- <?php if (have_posts()) : ?>
- <?php while (have_posts()) : the_post(); ?>
- //替換為
- <?php $posts=query_posts($query_string . '&posts_per_page=-1'); ?>
- <?php if (have_posts()) : ?>
- <?php while (have_posts()) : the_post(); ?>
|
新聞熱點
疑難解答
圖片精選