GeneratePressのWordPressテーマでGoogleカスタム検索エンジンを利用する

GeneratePressテーマで、WordPressのデフォルト検索をGoogleカスタム検索エンジンに切り替えたい理由は2つあります。

  • 静的なWordPressサイトのクライアント側ソリューションが必要です。
  • 関連性の高い結果を表示することで、検索体験を向上させたいと考えています。

Googleカスタム検索を追加する手順

  • WordPressにタイトル「検索結果」、パーマリンク「search」で新しいページを追加します。
  • SEOプラグインの指示に従い、検索結果ページをnoindexにする。
noindex search results page
見つからない?RankMathをAdvancedモードで再セットアップする
  • 検索ボックスと検索結果を表示するために、Text モードで以下の CSE コードを追加します。
<gcse:search enablehistory="false"></gcse:search>
  • CSEウェブサイトへのサインイン
  • 新しい検索エンジンの追加
Adding new Google Custom Search Engine
  • 検索結果に表示するサイトのURLをワイルドカード形式で指定します。
  • wwwかnon-wwwか、canonicalの通りにしてください。😉
sites to search
例えば、https://gulshankumar.net/* のパスから検索した結果を表示したい。
  • おめでとうございます。カスタム検索エンジンの作成に成功しました。
  • コントロールパネルに移動する
CSE created
  • “ルック&フィール “に移動する
  • Select Two Pagesレイアウト
  • 💾 セーブ&ゲットコード
Two Page Layout
Two Page Layout

検索URLのパラメータを設定する

  • 検索結果の詳細で、検索結果ページのURLとクエリパラメータを設定します。
setup search param urls
  • 保存してコードを取得]ボタンをクリックします。すると、Search Resultsのコードが表示されます。  Divの部分は無視して、最初のステップですでに追加しています。JavaScriptをコピーしてください。これをHookで使用します。
Copy CSE JS

WordPressにコードを設定する

  • GeneratePress Premiumで利用可能なElementsモジュールを有効にします。
Elements
  • 新しいHookを作成する
Hook
  • Custom Search Engine (English)」という名前を付けて、先ほどコピーしたJSを貼り付けます。
cse script
  • Googleカスタム検索エンジンからコピーしたJSコードを配置します。ブラウザで素早くJSを読み込むために、私自身はpreload部分を追加しています。パブリッシャー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>
  • wp_head フックの優先順位を 0 にして、スクリプトが HTML の head の最上部に配置されるようにします。
  • パフォーマンスに関しては、このJSが実際に必要とされるWordPressの検索結果ページとそれ以外のページでのみ読み込まれるように、Display Rulesを設定することができます。
Hook Page Rule

Googleカスタム検索結果の広告を非表示にする

  • 同様に、新しいHookを使用して、検索結果ページの良いデザインのためにインラインCSSの下に追加します。無料版では、迷惑な広告を隠すことができます。
<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>

WordPressの検索結果の表示は、https://gulshankumar.net/?s= で行っていることが分かっています。

そのため、Searchボックスのアクションパスを変更することが重要で、YoastはSite SearchのためにJSON-LDマークアップを追加しました。Code Snippetプラグインを使って、以下のスニペットを設置します。

// 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

正しいJSONパス

// 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' );

検索クエリに応じたページタイトルと見出しの表示

URLSearchParamsをベースにした以下のスニペットを提供してくれたJames Hibbardに感謝します。これはすべてのモダンブラウザで動作するはずです。

最初のステップで作成した「検索結果」ページ専用のGeneratePress Elementsを使って、wp_footerフックにスクリプトを配置することを確認してください。

<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>

これで、タイトルと見出しに検索クエリが表示されるようになりました。

Search Query

よくあるご質問

検索結果のリンクを強制的に同じタブで開くには?

Set Link Target to _self

Widget Search BoxやManuallyをCSEバージョンに変換する方法は?

Real Time Find and Replace Plugin “を使って、CSEの設定に従って名前とアクションパラメータを置き換えます。

お読みいただきありがとうございました。

コメントする

「GeneratePressのWordPressテーマでGoogleカスタム検索エンジンを利用する」への37件のフィードバック

    • 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 ..

        返信
  1. 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?

    返信
  2. 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?

    返信
  3. The awesome tutorial I have integrated Custom search results on my site, what you have shown is entirely unique. Thanks for this tutorial.

    返信
  4. 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.

    返信
  5. 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.

    返信
  6. 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.

    返信
    • May I know please what specific thing you wish to modify? Is it Search Results slug /search/ or what? Please elaborate.
      Thank you.

      返信