Google Custom Search plugin for Craft CMS 3.x
A Craft CMS plugin that incorporates a Google Custom Search into your website., (*1)
Google offers free and paid tiers for accessing their search results., (*2)
If you are looking for the Craft 2 version of this plugin, see the craft2
branch., (*3)
Requirements
This plugin requires Craft CMS 3.0.0 or later., (*4)
Installation
To install the plugin, follow these instructions., (*5)
-
Open your terminal and go to your Craft project:, (*6)
cd /path/to/project
-
Then tell Composer to load the plugin:, (*7)
composer require imarc/craft-googlecustomsearch
-
In the Control Panel, go to Settings → Plugins and click the “Install” button for googlecustomsearch., (*8)
Configuring
You will need a Search Engine ID and API Key from Google., (*9)
Search Engine ID - On the Custom Search Engine Control Panel, create a new search engine for the site you would like to integrate. Once created, you can retrieve your Search Engine ID from the Setup tab., (*10)
API Key - If you're using the free tier, visit the Google Developers Console and create a project for your search engine. Within your project, you’ll need to enable the Custom Search API from the APIs tab. Finally, on the Credentials tab, you will need to create a Public API access key by selecting the Create new Key option and choosing Server key. The API Key will now be available. If you're using a paid tier, you can find your API key in the Control Panel in the Business > XML & JSON tab., (*11)
The credentials can either be added from Craft's plugin settings or within config/googlecustomsearch.php
., (*12)
```(php)
<?php
return [
"apiKey" => getenv('GOOGLE_SEARCH_API_KEY'),
"searchEngineId" => getenv('GOOGLE_SEARCH_ENGINE_ID'),
];, (*13)
## Usage
In your twig template, retrieve search results from Google by passing it your search query, which you can then iterate over to display:
```(twig)
{% set response = craft.googlecustomsearch.performSearch('google') %}
Here is a complete example with pagination:, (*14)
```(twig)
{% extends "_layout" %}, (*15)
{% set query = craft.request.getParam('q') %}
{% set page = craft.request.getParam('page') ?: '1' %}
{% set title = "Search" %}, (*16)
{% if query %}
{% set response = craft.googlecustomsearch.performSearch(query, page) %}
{% set title = query ~ " - Search" %}
{% set totalPages = ceil(response.totalResults / response.perPage) %}
{% endif %}, (*17)
{% block content %}, (*18)
Search
{% if query %}
{% if response.results | length %}
Showing {{ response.start }}–{{ response.end }} of {{ response.totalResults }} results for {{ query }}
, (*19)
{% if totalPages > 1 %}
{% endif %}
{% else %}
Your search for “{{ query }}” didn’t return any results.
, (*21)
{% endif %}
{% endif %}
{% endblock %}
```, (*22)
Credits
Brought to you by Imarc, (*23)