2017-02-09 68 views
1

我想通过function.php动态生成goo.gl链接,当创建一个帖子时......但它没有使用本地主机上创建的链接更新字段..我只是不知道这个问题生成goo.gl不在本地主机上工作

function newlinks($post_id){ 
    $permaurl=get_permalink($post_id); 
    $shorturl=make_my_url($permaurl); 
    update_post_meta('$post_id','shorturl',$shorturl) 

    } 
    add_action('save_post', 'newlinks'); 
    function make_my_url($myurl) 
    { 

    //got te key from https://console.developers.google.com/iam-admin/projects 
    $key = 'AIzBP0'; 
    $googer = new GoogleURLAPI($key); 

    // Test: Shorten a URL 
    $shortDWName = $googer->shorten($myurl); 
    return $shortDWName; // returns the short url 

    } 

    // Declare the class 
    class GoogleUrlApi { 

     // Constructor 
     function GoogleURLAPI($key,$apiURL = 'https://www.googleapis.com/urlshortener/v1/url') { 
      // Keep the API Url 
      $this->apiURL = $apiURL.'?key='.$key; 
     } 

     // Shorten a URL 
     function shorten($url) { 
      // Send information along 
      $response = $this->send($url); 
      // Return the result 
      return isset($response['id']) ? $response['id'] : false; 
     } 
    // Send information to Google 
     function send($url,$shorten = true) { 
      // Create cURL 
      $ch = curl_init(); 
      // If we're shortening a URL... 
      if($shorten) { 
       curl_setopt($ch,CURLOPT_URL,$this->apiURL); 
       curl_setopt($ch,CURLOPT_POST,1); 
       curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url))); 
       curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json")); 
      } 
      else { 
       curl_setopt($ch,CURLOPT_URL,$this->apiURL.'&shortUrl='.$url); 
      } 
      curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 
      // Execute the post 
      $result = curl_exec($ch); 
      // Close the connection 
      curl_close($ch); 
      // Return the result 
      return json_decode($result,true); 
     }  
    } 

回答

0

你的代码是好的。我已经创建了自己的API密钥,并尝试了这一点,并且正常工作。这个问题可能在谷歌控制台。

请登录到https://developers.google.com/apis-explorer/?hl=pl#p/urlshortener/v1/并尝试在那里生成短网址。 Google应该要求您授权您之前创建的密钥。之后,代码应该可以正常工作。

+0

该代码似乎在线工作,但不在本地主机....我如何GT它在本地主机上工作...你测试本地主机? –

+0

是的,本地主机和控制台 –

+0

我需要在我的php.ini中进行任何更改吗? –

相关问题