The question:
I don’t need to search for pages in my site and only want to search posts, is there a way to do it? Thanks
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
The below should make the page post type no longer search-able.
function remove_pages_from_search() {
global $wp_post_types;
$wp_post_types['page']->exclude_from_search = true;
}
add_action('init', 'remove_pages_from_search');
Method 2
The following in functions.php also works well:
//Remove pages from search results
function mySearchFilter($query) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
add_filter('pre_get_posts','mySearchFilter');
Method 3
Here is code for removing specific pages from search in WordPress, add the following code in a function.php file
Just replace the array with your page ID’s
function remove_pages_from_search($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post__not_in', array(3031,2958,2926));
}
}
}
add_action('pre_get_posts','remove_pages_from_search');
Method 4
put this in your search.php
<?php if (is_search() && ($post->post_type=='page')) continue; ?>
right below this code -> <?php if ( have_posts() ) : while ( have_posts() ) : the_post();?>
you can find more on here http://wordpress.org/support/topic/possible-search-only-posts-exclude-pages
Method 5
This solution follows (respects) WP API rather than modifying internal vars directly.
Notice that this way you can also include (overwrite registration) types or change registration arguments provided in register_post_type()
. Check out 'exclude_from_search'
description in docs.
/**
* Filter object types in search results.
*
* @param array $args Array of arguments for registering a post type.
* See the register_post_type() function for accepted arguments.
* @param string $type Post (object) type key (e.g. 'post', 'page', 'attachment'...,
* or any custom post type registered).
* @return array Filtered type attributes.
*/
function _filter_search_types( $args, $type ) {
$exclude_types = array( 'page' );
if ( in_array( $type, $exclude_types, true ) ) {
$args['exclude_from_search'] = true;
}
return $args;
}
if ( ! is_admin() ) {
add_filter( 'register_post_type_args', __NAMESPACE__ . '_filter_search_types', 10, 2 );
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0