There are two reasons why you may want to replace the default WordPress search to Google Custom Search Engine in GeneratePress Theme.
- You want to improve the search experience by displaying highly relevant results.
- You need a client-side solution for a Static WordPress site.
Steps for adding Google Custom Search
- Add a new page with Title “Search Results” and permalink “search” in your WordPress.
- Noindex Search Results page following instructions from your SEO plugin.
- add below CSE code in the Text mode to display Search box and results.
<gcse:search enablehistory="false"></gcse:search>
- Sign in to CSE website
- Add a new Search Engine
- Provide the URL of site in the wildcard format to display it in the Search results
- Take care of www or non-www as per your canonical 😉
- Congratulations! You’ve successfully created your Custom search engine.
- Go to Control Panel
- Go to “Look and Feel”
- Select Two Pages layout
- 💾 Save & Get code
Configure Search URL Parameters
- In Search Results Details, set Search Results page URL and Query parameter.
- Click Save & Get Code button. You will see Search Results code. Ignore the Div part, we have already added in first step. Just copy the JavaScript. We are going to use it with Hook.
Setup code inside WordPress
- Enable Elements module which is available in the GeneratePress Premium.
- Kindly go to Appearance > Elements > Hook
- Create a new hook element titled Google Programmable Search Engine (Formerly, Custom Search Engine). Ref: screenshot
- Place the JS code that you copied in the last step from Google Custom Search Engine website. There are typically two types of code one for Search Box (you really do not need it), and another for Search Results (This is what we need to use for our search result pages). Not to get confused, I have added preload part myself for loading JS quickly in the browser. Make sure to replace with your publisher ID.
<link rel="preload" href="https://cse.google.com/cse.js?cx=partner-pub-XXXXXXXXXXX:YYYYYYYY" as="script">
<script async src="https://cse.google.com/cse.js?cx=partner-pub-XXXXXXXXXXX:YYYYYYYY"></script>
- Use
wp_head
hook with highest priority value 0 to ensure script get placed at the top section of head in the HTML. - Concerning performance, we can set Display Rules to load this JS only on WordPress Search Results page where it is actually required and non-other page.
Hide Advertisement of Google Custom Search Results
- Again using Elements > Settings: wp_head > Display Rule: Page > Search Results (which you’ve created in early steps above)
- Please add below inline CSS for good design of Search Results page. It will hide annoying advt as well in the free version.
<style>
/* Google search results */
.gs-webResult {
border: 0px solid #eee;
padding: 1em;
}
/* Do no display the count of search results */
.gsc-result-info {
display: none;
}
/* Hide the Google branding in search results */
.gcsc-branding {
display: none;
}
/* Hide the thumbnail images in search results */
.gsc-thumbnail {
display: none;
}
/* Hide the snippets in Google search results */
.gs-snippet {
font-size: 16px;
}
/* Change the font size of the title of search results */
.gs-title a {
font-size: 18px !important;
text-decoration: none !important;
}
.gs-webResult div.gs-visibleUrl-long {
font-size: 16px !important;
}
/* Change the font size of snippets inside search results */
.gs-title b, .gs-snippet b {
font-weight: normal;
}
/* Highlight the pagination buttons at the bottom of search results */
.gsc-cursor-page {
font-size: 1.3em;
padding: 4px 8px;
border: 2px solid #ccc;
}
.gsc-adBlockVertical, .gsc-adBlock {
/* this hides both the top and right ad blocks*/
display: none !important;
}
.gsc-thinWrapper {
/* this gives you use of the whole block, as opposed to 69% google gives*/
width: 100%;
}
.gsc-result-info-container {
display: none;
}
td.gsc-twiddleRegionCell.gsc-twiddle-opened {
display: none;
}
td.gsc-configLabelCell {
display: none;
}
.gsc-above-wrapper-area {
border-bottom: 0px solid #E9E9E9!important;
padding: 0px!important;
}
.gsc-resultsRoot.gsc-tabData.gsc-tabdActive table {
margin-bottom: 0px !important;
}
.gsc-resultsRoot.gsc-tabData.gsc-tabdActive tbody {
border-bottom: 0px solid #ddd !important;
}
.gsc-result .gs-title {
height: 1.5em !important;
}
.gs-webResult.gs-result a.gs-title:link, .gs-webResult.gs-result a.gs-title:link b, .gs-imageResult a.gs-title:link, .gs-imageResult a.gs-title:link b {
border-bottom: 0px solid #4199FB;
}
.gs-webResult {
border: 0px solid #eee !important;
padding: 0em !important;
}
.cse .gsc-control-cse, .gsc-control-cse {
margin-top: 18px !important;
}
div.gcsc-branding {
display: none;
}
.cse .gsc-control-cse, .gsc-control-cse {
padding-top: 0 !important;
padding-bottom: 30px !important;
}
.gsc-webResult .gsc-result {
padding: 0px 0 10px 0 !important;
}
table.gsc-search-box td {
border: 0px !important;
}
.gsc-input-box table {
margin: 0px ;
}
.gcsc-find-more-on-google {
display: none !important;
}
.gsib_a {
padding: 9px 9px 9px 9px !important;
}
.cse .gsc-search-button-v2, .gsc-search-button-v2 {
border-color: #da0000 !important;
background-color: #da0000 !important;
padding: 10px 19px 10px 19px !important;
}
button.gsc-search-button.gsc-search-button-v2 svg {
width: 18px;
height: 13px;
}
.gsc-input-box {
padding-top: 0px !important;
padding-bottom: 0px !important;
}
.cse .gsc-control-cse, .gsc-control-cse {
padding: inherit !important;
}
</style>
By default, WordPress display the search results at https://www.gulshankumar.net/?s=query
Therefore, it is important to change action path for Search box and Yoast added JSON-LD markup for the Site Search. You should place below snippet using Code Snippets plugin. Alternatively, you may use Fluent Snippets, or WP Code as you prefer.
For the modal search box (recommended)
GeneratePress has switched to a modal search box for some reasons. This is the updated snippet for it.
add_action('wp',function(){
remove_action( 'generate_inside_search_modal', 'generate_do_search_fields');
add_action( 'generate_inside_search_modal', 'custom_do_search_fields' );
});
function custom_do_search_fields() {
?>
<form role="search" method="get" class="search-modal-form" action="<?php echo esc_url( home_url( '/search/' ) ); ?>">
<label for="search-modal-input" class="screen-reader-text"><?php echo apply_filters( 'generate_search_label', _x( 'Search for:', 'label', 'generatepress' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></label>
<div class="search-modal-fields">
<input id="search-modal-input" type="search" class="search-field" placeholder="<?php echo esc_attr( apply_filters( 'generate_search_placeholder', _x( 'Search …', 'placeholder', 'generatepress' ) ) ); ?>" value="<?php echo get_search_query(); ?>" name="q" />
<button aria-label="<?php echo esc_attr( apply_filters( 'generate_search_button', _x( 'Search', 'submit button', 'generatepress' ) ) ); ?>"><?php echo generate_get_svg_icon( 'search' ); // phpcs:ignore -- Escaped in function. ?></button>
</div>
<?php do_action( 'generate_inside_search_modal_form' ); ?>
</form>
<?php
}
For the older version of GP premium
Step 1. we need to restore the previous settings.
add_filter( 'option_generate_settings', function( $settings ) {
$settings['nav_search'] = 'enable';
return $settings;
} );
Step 2. Then apply below code.
// Change Search path in the GeneratePress Theme
add_filter( 'generate_navigation_search_output', function() {
printf(
'<form method="get" class="search-form navigation-search" action="%1$s">
<input type="search" placeholder=" Search" class="search-field" value="%2$s" name="q" title="%3$s" />
</form>',
esc_url( home_url( '/search/' ) ),
esc_attr( get_search_query() ),
esc_attr_x( 'Search', 'label', 'generatepress' )
);
} );
// Other theme? Use Real Time Find and Replace Plugin
Okay, Let’s move on to the next steps.
Update the query parameter in the JSON-LD markup added by the SEO plugin
JSON-LD is a simple format for adding structured data that helps search engines understand your website better. Most SEO plugins automatically add JSON-LD to the <head>
section of your webpage to improve features like rich search results, such as star ratings or event details.
- You should update the markup by placing below code using the Code Snippets plugin.
// For Yoast SEO
function yst_change_json_ld_search_url() {
return trailingslashit( home_url() ) . 'search/?q={search_term_string}';
}
add_filter( 'wpseo_json_ld_search_url', 'yst_change_json_ld_search_url' );
// For Rankmath
function gk_change_json_ld_search_url() {
return trailingslashit( home_url() ) . 'search/?q={search_term_string}';
}
add_filter( 'rank_math/json_ld/search_url', 'gk_change_json_ld_search_url' );
Display the Page Title and Heading as per Search Query
Thanks to James Hibbard who provided me below snippet which is based on URLSearchParams. This should work for all modern browsers.
Again using Elements > Hook > Make sure to place script with wp_footer
hook using GeneratePress Elements specifically for ‘Search Results’ page that we created in first step.
<script>
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const searchTerm = urlParams.get('q');
if (searchTerm) {
const heading = document.querySelector('h1');
const title = document.querySelector('title');
heading.textContent = `Search Results for ${searchTerm}`;
title.textContent = `Search Results for ${searchTerm}`;
}
</script>
Now you can see Search Query in Title and Heading.
FAQs
How to force the Search Result link to open in the same tab?
Set Link Target to _self
How to convert Widget Search Box or Manually to the CSE version?
Replace name and action parameter as per CSE setup via Real Time Find and Replace Plugin.
P.S. Thank you for reading my tutorial. I deeply regret not being able to keep it up to date, but I’ll address it soon.
Hi Gulshan. Thanks a lot for the guide. I have some genuine feedback and I hope you reflect the changes requested here.
First, there is an error the updated snippet for the GeneratePress Search Modal box. We need the query parameter ?q.
The code presently mentions [value=”” name=”s” />]. That ‘name’ needs “q” next to it for GSC to actually work. The final code should be – [value=”” name=”q” />] This minor problem had me scratching my head a good hour until I decided to try and read it.
Secondly, this post needs to be updated for better clarity and freshness. Everything went smooth until I scrolled down to the section “Hide Advertisement of Google Custom Search Results”. From that point onward, it is not mentioned clearly where one is supposed to enter the code. Instead of writing ‘create a new hook’, you could write “Go to Elements>Hooks and create a new hook titled XYZ on wp_head. Set it to Display on the Search Results page.” Similarly, for the snippets, the extra lines need to be added. Beginners need that kind of simplification.
Thirdly, Google has changed the UI of the its programmable search engine site resulting in the shuffling of a lot of things. If you can, do consider updating the CSE images posted at the beginning of this post.
Finally, there should be a video accompanying this guide. A new one.
Thank you sincerely for your detailed and constructive feedback — it’s one of the most helpful comments I’ve received. I completely understand the importance of keeping the guide clear, up-to-date, and beginner-friendly.
I’ve addressed the error in the search parameter by replacing
name="s"
withname="q"
for proper functionality with Google Search Console. I apologize for the oversight and appreciate your patience in identifying it.Regarding the “Hide Advertisements” section, I’ll clarify the instructions to specify that the custom CSS should be added using Elements > Hook with
wp_head
settings, targeting only the search results page. I’ll also include detailed steps and examples to make this process straightforward for users of all experience levels.You’re also right about the changes in Google’s Programmable Search Engine interface; updating the images at the start of the post is a priority. Lastly, I’ll work on creating an accompanying video to enhance the usability of this guide.
Thank you once again for your valuable insights and for helping improve the guide for everyone.
Hey – many thanks for this guide. I’ve been working on making my WP site static, but was having big issues with getting search working – and this guide has hopefully solved my issues!
The one challenge I did have getting it working was getting the GP modal box to go to the correct search results page – after doing the steps as detailed it wouldn’t work, I’d hit search and would not get redirected to the search results page.
Seemed to be an issue with the search url being: /?s=
When it needed to be: /search/?q=
In the GP modal code, I found that changing this:
name=”s” />
to:
name=”q” />
fixed it and it worked fine now. Hopefully this is the correct solution?!
Thank you for your feedback and for sharing your solution! Yes,
name="q"
is indeed the correct format for Google Custom Search Engine (CSE) compatibility, and it’s great to hear that switching fromname="s"
toname="q"
worked for you. This is the most suitable approach when integrating CSE, and I’m glad the guide helped you resolve the issue.Sir, if possible update this post, because currently lots of such things are missing in Custom Search Engine for website.
Sir, i am not able to perfectly use this, if possible make a video.
It appears that something is unclear due to changes in the CSE website’s UI. I’ll make sure to update this article with the latest screenshots. Thank you for your feedback.
Hi Gulshan
I followed your detailed tutorial and everything was fine until GP Pro 2.4.1, I don’t know for sure when the Google Custom Search Engine stopped working, but I guess this could be the reason. Is your article updated for GP Pro 2.4.1? Thanks
Thank you for following my tutorial. I’ve updated the article to include information on using the Google Custom Search Engine with the modal search box, which should be compatible with the latest version of GeneratePress theme. Additionally, I’ve included guidance for the older classic navigation search.
I want to show ads in search results but also want the CSS design, what Should I remove from the “HideAdvertisement of Google Custom Search Results” CSS code to display search results?
Is it just these 2 ?
.gsc-adBlockVertical, .gsc-adBlock {
/* this hides both the top and right ad blocks*/
display: none !important;
}
.gsc-thinWrapper {
/* this gives you use of the whole block, as opposed to 69% google gives*/
width: 100%;
}
I follow this method and add it to my website but suddenly it is not working. Search page shows empty! Can you help to solve this!!
Thank you so much Sir Gulshan Kumar! I have successfully implemented it on my site https://www.teacherph.com/
It works well paired with GeneratePress theme.
Good to know. Thanks for your kind feedback.
Can i change ” Correct JSON path” permanently without this plugin?
Hi Mahi, Yeah, same snippet can be added in Theme
functions.php
last line but it’s a poor idea. When theme will update, that will be lost. That’s a reason, I have recommended Code Snippets plugin way. It’s a reputed plugin with decent support from author. Use it with confidence.Thank you for your prompt response. I have successfully setup it by watching your tutorial. But sometimes it doesn’t work in mobile view. Sometimes I open the search page directly but the search box doesn’t show ..
I’m using Hueman Theme. Any alternative code for this.
Please check with that Theme Author.
How to increase the maximum text length of the snippet??
CSE doesn’t offer a way to increase meta description length.
Hi Gulshan, Thanks for this post. It’s worked and I loved the method. I wanna ask how can I hide the page which we have created in the beginning for search results.
What did you do with the page? I can’ find it on your website.
can I delete that “search page” from my site?
Ankit, that’s the page where the code to display the search results has to be put. When someone searches something, he/she is taken to that page and that’s where the search results appear.
Set noindex.
Okay, thanks.
Thank you for the great article, Gulshan! I am actually using the Rank Math plugin. Can you show me how to change the searchAction target from /?s= to /search/?q=
I can change it by directly editing the plugin file, which is located at includes > modules > schema > snippets > class-website.php file, but in that case, the change will again be restored in case there’s a new update to the plugin.
Is there a permanent solution?
Just updated my article, it has snippet for RankMath.
Thanks, it works!
The awesome tutorial I have integrated Custom search results on my site, what you have shown is entirely unique. Thanks for this tutorial.
Glad to hear. Thank you Milind.
How can i enable this in my newspaper theme?
Try using Real Time Find and Replace Plugin to update Search Box. Rest process is same.
In generatepress you have used elements to hook the JS. How can I do it in newspaper theme to hook that JS?
You can use Theme Options (Header/Footer) field for adding that code or manually place inside page where required using HTML tag.
Ok thank you for this. O will try to do it.
Hi, I followed the above tutorial but the google search is not working on my site. I am using GenertePress Pro.
Could you please help me out.
I have updated my article with video. Please find in this tutorial.
A lot of useful information is shared for people like us. Thanks for sharing
Good to know. Thanks for your kind feedback. 😊
Thank you for writing an awesome tutorial.
I have a few questions
1. How to include the search box above the result page like yours? ==> https://i.imgur.com/gAvg84e.png
2. When someone types the wrong URL and then it will get redirected to the 404 pages. There is a search box and that search box is using WordPress default search. so, how to convert that search box too into CSE?
Thank You.
Hi, I have updated this article.
Let me know if you have any additional queries.
Thanks & Regards,
Gulshan
👏👏👏👏
add_filter( ‘generate_navigation_search_output’, function()
I believe this takes search input and displays the result in /search/ page. This is not working with genesis.
This Filter works in GeneratePress. Please check with Genesis developer to find relevant code.
Thanks, got it working. Thank you for the great tutorial 🙂
How to modify snippets at step 18 for the same? I’m stuck. Please help.
May I know please what specific thing you wish to modify? Is it Search Results slug
/search/
or what? Please elaborate.Thank you.
Can I add this to Genesis theme?
Of course, yes.