Встроенная поисковая система WordPress часто упоминается как одно из слабых мест популярной блог-платформы. В этой статье я собрал несколько фрагментов кода, чтобы сделать поисковую систему WordPress намного лучше.
Перенаправить на первый пост, если найден только один пост
Давайте начнем с удобного фрагмента, который автоматически перенаправит читателя на пост, если найден только один пост. Просто вставьте его в свой 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 ) ); } } }
Источник: http://www.paulund.co.uk/redirect-search-results…
Показать количество результатов в поиске WordPress
Когда поиск выполняется в вашем блоге, WordPress не возвращает количество найденных результатов. Тем не менее, это может быть полезно для человека, который сделал поиск.
Чтобы отобразить количество результатов, откройте ваш search.php
файл. В ней ищите следующее:
<h2 class="pagetitle">Search Results</h2>
Теперь замените его на:
<h2 class="pagetitle">Search Results for <?php /* Search Count */ $allsearch = &new WP_Query("s=$s&showposts=-1"); $key = wp_specialchars($s, 1); $count = $allsearch->post_count; _e(''); _e('<span class="search-terms">'); echo $key; _e('</span>'); _e(' — '); echo $count . ' '; _e('articles'); wp_reset_query(); ?></h2>
Источник: http://www.problogdesign.com/wordpress/3-codes-for-a-far-better…
Включить искомый текст в результаты поиска
Here is an easy way to make your search results more user-friendly: Enlight searched text.
To do so, open your search.php
file and find the the_title()
function. Replace it with:
echo $title;
Now, just before the line you just modified, add this code:
<?php $title = get_the_title(); $keys= explode(" ",$s); $title = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt">\0</strong>', $title); ?>
Save the search.php
file and open style.css
. Append the following line to it:
strong.search-excerpt { background: yellow; }
That’s all. Better, isn’t it?
Source: http://yoast.com/wordpress-search/
Limit posts per page on search
By default, WordPress outputs 10 posts per page on the search results page. If you need to change this number, just paste the following code in your functions.php
file. Replace the number on line 3 by the desired number of posts to be displayed.
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');
Source: http://wordpress.org/support/topic/limit-post-per-search-page
Search within post type only
If you want to force the search engine to search only within a specific post type, here is the solution. Paste the code below into your functions.php
file after you changed the post type name on line 4.
function SearchFilter($query) { if ($query->is_search) { // Insert the specific post type you want to search $query->set('post_type', 'feeds'); } return $query; } // This filter will jump into the loop and arrange our results before they're returned add_filter('pre_get_posts','SearchFilter');
Source: http://www.hongkiat.com/blog/wordpress-search-plugin-snippet/
Limit search to specific categories
Is it also possible to limit search to specific categories. To do so, just replace the categories IDs on line 3 and paste the following code on your search.php
template:
<?php if( is_search() ) : $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; query_posts("s=$s&paged=$paged&cat=1,2,3"); endif; ?>
Source: http://www.wprecipes.com/how-to-limit-search-to-specific-categories
Completely shut down WordPress search
Although search is a really useful feature on most websites, sometimes you simply don’t need it at all. Did you knew that you could completely shut down WordPress search? Just include the function below in your functions.php
file.
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;" ) );
Source: http://wpengineer.com/1042/disable-wordpress-search/
Make your search results unlimited
As I already stated before, the fact that WordPress displays 10 posts by default on the search results page can be annoying. If you’d like to display unlimited search results on the same page, here’s an easy way to do it.
In search.php
, find the code below:
<?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?>
Once you found it, replace it by this:
<?php $posts=query_posts($query_string . '&posts_per_page=-1'); ?> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?>
That’s all. You’re done!
Source: http://wphacks.com/how-to-make-wordpress-search-results-unlimited/