Archived topic
Limit Search Results to Just Posts
8 replies · Started by Heather on August 22, 2019
Hi there,
I am trying to limit my search results to just the posts that include the search word. Right now it is bringing up both posts as well as pages (including hidden ones)/anything with the word. See this example photo, where I searched for blog but it shows 3 pages with the word blog, and a post. Is there a way to change this somewhere in the backend or in the php itself? As I have not been able to find it in the customize or settings.

Hi there,
Can you try this PHP snippet?
add_filter( 'generate_navigation_search_output', function() {
printf(
'<form method="get" class="search-form navigation-search" action="%1$s">
<input type="search" class="search-field" value="%2$s" name="s" title="%3$s" />
<input type="hidden" name="post_type" value="post" />
</form>',
esc_url( home_url( '/' ) ),
esc_attr( get_search_query() ),
esc_attr_x( 'Search', 'label', 'generatepress' )
);
} );
Adding PHP: https://docs.generatepress.com/article/adding-php/
Let me know if this helps :)
Could you specify where to put this php function? I tried putting it in functions.php and in the search.php and it did not work.
We are trying to limit the use of plugins so downloading a code snippet plugin is something I am trying to avoid.
The search is the built in WP search widget. Let me know if you have a better idea of where to put this code.
Ahh I thought you are referring to GP's navigation search.
If it's a WordPress default search widget then this should help:
https://www.wpbeginner.com/wp-tutorials/how-to-limit-search-results-for-specific-post-types-in-wordpress/
If you don't want to use Code Snippets (should have minimal impact on your site), then you will need to create a child theme and add it to the function.php file of your child theme:
https://docs.generatepress.com/article/using-child-theme/
Thanks, that code from the link worked after removing 'posts' from the array!
No problem :)
No problem :)
This works too
function remove_pages_from_search() {
global $wp_post_types;
$wp_post_types['page']->exclude_from_search = true;
}
add_action('init', 'remove_pages_from_search');
Thanks for sharing :)