首页 > 解决方案 > 提交 Google 自定义搜索

问题描述

我正在使用不再工作的旧谷歌自定义搜索代码,我想检查如何修复代码以使用新的谷歌自定义搜索。

我尝试了很多没有运气的事情,这是我今天的代码:

// Google Search (deprecated - to remove)
if ($task == 'search' && $params->get('googleSearch'))
{
    $language = JFactory::getLanguage();
    $lang = $language->getTag();
    // Fallback to the new container ID without breaking things
    $googleSearchContainerID = trim($params->get('googleSearchContainer', 'k2GoogleSearchContainer'));
    if($googleSearchContainerID == 'k2Container'){
        $googleSearchContainerID = 'k2GoogleSearchContainer';
    }
    $document->addScript('https://www.google.com/jsapi');
    $document->addScriptDeclaration('
        google.load("search", "1", {"language" : "'.$lang.'"});
        function OnLoad(){
            var searchControl = new google.search.SearchControl();
            var siteSearch = new google.search.WebSearch();
            siteSearch.setUserDefinedLabel("'.$application->getCfg('sitename').'");
            siteSearch.setUserDefinedClassSuffix("k2");
            options = new google.search.SearcherOptions();
            options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
            siteSearch.setSiteRestriction("'.JURI::root().'");
            searchControl.addSearcher(siteSearch, options);
            searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
            searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
            searchControl.draw(document.getElementById("'.$googleSearchContainerID.'"));
            searchControl.execute("'.JRequest::getString('searchword').'");
        }
        google.setOnLoadCallback(OnLoad);

标签: phpformssubmitgoogle-custom-search

解决方案


将旧系统更新为新系统。它很容易使用。

按照这个链接; https://developers.google.com/custom-search/docs/tutorial/creatingcse

然后使用此链接单击此控制面板:https://cse.google.com/create/new 创建后在您的网站中使用以下enter code here代码:

<script>
  (function() {
    var cx = '012345678901234567890:inyoqlhp8ya'; /* 21 Numbers code */
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
  })();
</script>
<gcse:search></gcse:search>

推荐阅读