How to Limit WordPress Search to Homepage Content Only (Exclude Other Pages/Post
-
Hi,
How can I make my WordPress search bar search only within my homepage content (not other pages/posts) when someone searches for a specific keyword?The blog I need help with is: (visible only to logged in users)
-
Hi there! To limit your search results to only your homepage content for 7brrewmenu.com, you can add a small function to your theme’s functions.php file. By using the pre_get_posts filter, you can instruct the search query to only include the ID of your static front page (which the code fetches automatically using get_option(‘page_on_front’)). This ensures that when a customer searches for a specific keyword or menu item, WordPress ignores all other posts or background pages and only scans the homepage. If you aren’t comfortable editing theme files directly, I recommend using a plugin like WPCode to safely add this snippet. Let me know if you’d like me to provide the specific code for you to copy and paste!
-
Hi James3265166,
Thanks for your detailed answer. Well yes please provide me that specific code, if you have, so that I can paste it to check whether it works or not. -
No problem at all! Here is the specific code snippet you can use. The safest way to add this is by installing a free plugin like WPCode (or Code Snippets) and creating a new ‘PHP Snippet,’ but you can also add it to your child theme’s functions.php file if you prefer. This code automatically finds your specific Homepage ID and tells WordPress to ignore all other pages when running a search:
add_filter( ‘pre_get_posts’, function( $query ) { // Only run this on the front-end search results if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) { // Get the ID of the static homepage $front_page_id = get_option( ‘page_on_front’ ); // If a homepage is set, limit search to that ID only if ( $front_page_id ) { $query->set( ‘post_type’, ‘page’ ); $query->set( ‘post__in’, array( $front_page_id ) ); } }});
Once you save that, try searching for a specific term on your menu to verify it only pulls up the homepage. Let me know if that works for you!
-
-
Actually, you should not paste that into a ‘Custom HTML’ block. Because this is PHP code, it needs to be added to your site’s core logic rather than inside a page’s content area. If you paste it into an HTML block, it will just show up as plain text on your website instead of actually functioning.The best way to test it is to use the WPCode plugin I mentioned: go to ‘Code Snippets’ in your sidebar, click ‘Add New,’ select ‘PHP Snippet,’ and paste the code there. Once you click ‘Activate,’ it will immediately start filtering your search results. Alternatively, you can add it to the bottom of your theme’s functions.php file, but using a plugin is much safer because it won’t be deleted when you update your theme!”