Wordpress google cse api搜索结果

时间:2017-03-23 07:07:38

标签: javascript php json wordpress

我的朋友通过谷歌自定义搜索使用javascript向我发送一个示例,此结果将仅在提交搜索表单时显示来自网站的所有相关帖子/内容。

这是代码:

<html>
<head>
<script>
var hndlr = function($response) {
  for (var i = 0; i < $response.items.length; i++) {
    var item = $response.items[i];

    // in production code, item.htmlTitle should have the HTML entities escaped.
    document.getElementById("content").innerHTML += "<br>";
    document.getElementById("content").innerHTML += "<br> Title : " + item.title;
    document.getElementById("content").innerHTML += "<br> ==================================== ";

    if (item.pagemap.hreview) {
      for (var j = 0; j < item.pagemap.hreview.length; j++) {
        document.getElementById("content").innerHTML += "<br>" + j + ": " + item.pagemap.hreview[j].description;
      }
      document.getElementById("content").innerHTML += "<br>";
    }
  }
}
/*
var curltestPHPonly = function() {
  $ch = curl_init();
  // set url 
  curl_setopt($ch, , "https://www.googleapis.com/customsearch/v1?key=XXXXX here is your key xxxxxxxxxxx&q=wine&callback=hndlr");
  curl_exec($ch);
}*/

var searchdata;

var curltest = function() {
  searchdata = document.getElementById('curlinput');
  var urltest = document.createElement('script');
  urltest.type = 'text/javascript';
  urltest.async = true;
  urltest.src = 'https://www.googleapis.com/customsearch/v1?key=XXXXX' // here is your key xxxxxxxxxxx&cx=xxxxxxx here is yor sc id + '&q=' + searchdata.value + '&callback=hndlr';
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(urltest, s);
}
</script>
</head>
<body>

  <form action="javascript:curltest()">
    Iuput Search Name :<br>
    <input type="text" name="firstname" value="" id="curlinput">
    <br>
    <br>
    <input type="submit" value="Submit">
  </form>

  <div id="content"></div>

</body>

</html>

然后我尝试使用gcse api插件在我的wordpress网站上执行此操作,但结果只显示标题和部分内容以及“阅读更多 - &gt;” ,

如何修改它以获取/显示所有内容?

这是插件的php文件:

function gcse_request($test = false)
{

    global $wp_query;
    $options = get_option('gcse_options');
    $q       = html_entity_decode(get_search_query());

    if(isset($options['key']) && $options['key'] &&
        isset($options['id']) && $options['id']) {

        // Build URL
        $num    = isset($wp_query->query_vars['posts_per_page']) &&
            $wp_query->query_vars['posts_per_page'] < 11 ?
            $wp_query->query_vars['posts_per_page'] : 10;
        $start  = isset($wp_query->query_vars['paged']) &&
            $wp_query->query_vars['paged'] ?
            ($wp_query->query_vars['paged']-1)*$num+1 : 1;
        $params = http_build_query(array(
            'key'         => trim($options['key']),
            'cx'          => trim($options['id']),
            'alt'         => 'json',
            'num'         => $num,
            'start'       => $start,
            'prettyPrint' => 'false',
            'q'           => $q));
        $url    = 'https://www.googleapis.com/customsearch/v1?'.$params;

        // Check for and return cached response
        if($response = get_transient('gcse_'.md5($url))) {
            return json_decode($response, true);
        }

        // Request response
        if(is_wp_error($response = wp_remote_get($url, array('sslverify' => false)))) {
            return array('error' => array('errors' =>
                array(array('reason' => $response->get_error_message()))));
        }
    }

    // Save and return new response
    if(isset($response['body'])) {
        set_transient('gcse_'.md5($url), $response['body'], 3600);
        return json_decode($response['body'], true);
    }
    else {
        return array();
    }
}

/**
 * Search Results
 *
 * @since 1.0
 *
 */
function gcse_results($posts, $q) {
    if($q->is_single !== true && $q->is_search === true) {
        global $wp_query;

        $response = gcse_request();
        if(isset($response['items']) && $response['items']) {

            $results = array();
            $options = get_option('gcse_options');
            foreach($response['items'] as $result) {
                if(!isset($options['match']) && $id = gcse_url_to_postid($result['link'])) {
                    $post = get_post($id);
                }
                else {
                    $mime = false;
                    if(!empty($result['mime'])) {
                        switch($result['mime']) {
                            case "application/pdf":
                                $mime = "PDF";
                                break;
                            case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
                            case "application/vnd.openxmlformats-officedocument.presentationml.template":
                            case "application/vnd.openxmlformats-officedocument.presentationml.slideshow":
                            case "application/vnd.ms-powerpoint.addin.macroEnabled.12":
                            case "application/vnd.ms-powerpoint.presentation.macroEnabled.12":
                            case "application/vnd.ms-powerpoint.template.macroEnabled.12":
                            case "application/vnd.ms-powerpoint.slideshow.macroEnabled.12":
                            case "application/vnd.ms-powerpoint":
                                $mime = "PPT";
                                break;
                            case "application/msword":
                            case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
                            case "application/vnd.openxmlformats-officedocument.wordprocessingml.template":
                            case "application/vnd.ms-word.document.macroEnabled.12":
                            case "application/vnd.ms-word.template.macroEnabled.12":
                                $mime = "DOC";
                                break;
                            case "application/vnd.ms-excel":
                            case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
                            case "application/vnd.openxmlformats-officedocument.spreadsheetml.template":
                            case "application/vnd.ms-excel.sheet.macroEnabled.12":
                            case "application/vnd.ms-excel.template.macroEnabled.12":
                            case "application/vnd.ms-excel.addin.macroEnabled.12":
                            case "application/vnd.ms-excel.sheet.binary.macroEnabled.12":
                                $mime = "XLS";
                                break;
                        }
                    }
                    $post = (object)array(
                        'post_type'      => 'page',
                        'post_title'     => $result['title'],
                        'post_author'    => '',
                        'post_date'      => '',
                        'post_status'    => 'published',
                        'post_excerpt'   => $result['snippet'],
                        'post_content'   => $result['htmlSnippet'],
                        'guid'           => $result['link'],
                        'post_type'      => 'search',
                        'ID'             => 0,
                        'comment_status' => 'closed',
                        'mime'           => $mime,
                    );

                    // Adding in the featured image. You can use it if you'd like.
                    if(isset($result['pagemap']) && isset($result['pagemap']['cse_image']['0'])) {
                        $post->cse_img = $result['pagemap']['cse_image'][0]['src'];
                    }
                }
                $results[] = $post;
            }



            $post = '';
            // Set results as posts
            $posts = $results;
            $results = '';
            // Update post count
            $wp_query->post_count = count($posts);

            $wp_query->found_posts = $response['searchInformation']['totalResults'];

            // Pagination
            $posts_per_page = $wp_query->query_vars['posts_per_page'] < 11 ?
                $wp_query->query_vars['posts_per_page'] : 10;
            $wp_query->max_num_pages = ceil(
                $response['searchInformation']['totalResults'] /
                $posts_per_page);

            // Apply filters
            add_filter('the_permalink', 'gcse_permalink');
        }
    }
    return $posts;
}
if(!is_admin()) {
    // Modifies results directly after query is made
    add_filter('posts_results', 'gcse_results', 99, 2);
}

/**
 * URL to Post ID
 *
 * @param string $url
 *
 * @since 1.0
 *
 * @see url_to_postid
 * @see http://betterwp.net/wordpress-tips/url_to_postid-for-custom-post-types/
 *
 * @return int
 */
function gcse_url_to_postid($url)
{
    // TODO: Check url to post id map cache

    return url_to_postid($url);
}

/**
 * Permalink Filter
 *
 * @since 1.0
 *
 * @param string $the_permalink
 *
 * @return string
 *
 */
function gcse_permalink($the_permalink)
{
    if(function_exists('is_main_query') && is_main_query() && $the_permalink == '') {
        global $post;
        return $post->guid;
    }
    else {
        return $the_permalink;
    }
}

0 个答案:

没有答案