在wordpress插件中包含Google api客户端


Include Google api client in wordpress plugin

我使用谷歌分析的谷歌api php客户端库,当我在简单的php文件中使用它时,它的工作很好。这是代码

<?php 
include_once "templates/base.php";
session_start();
set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
$client_id = '';
$client_secret = '';
$redirect_uri = '';
$apikey='';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey($apikey);
$client->setAccessType("offline");
$client->setApprovalPrompt("force");
$client->setScopes('https://www.googleapis.com/auth/analytics');
$service = new Google_Service_Analytics($client);
if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_REQUEST['action'])) {
  unset($_SESSION['access_token']);
  $client->revokeToken();
  $authUrl = $client->createAuthUrl();
}
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
  $b = json_decode($client->getAccessToken());
  print_r($b->refresh_token);
  $client->refreshToken($b->refresh_token);
} else {
  $authUrl = $client->createAuthUrl();
}
?>

但当我在wordpress插件中使用时,它为文件包含提供了许多错误。如何在wordpress插件中包含文件?这里是WordPress代码包括文件

class postAnalytics
{
    public function __construct()
    {
            require_once 'Google/Client.php';
    require_once 'Google/Service/Analytics.php';
    }

}

这是错误

警告:require_one(Google/Auth/AssertionCredentials.php(:失败打开流:中没有这样的文件或目录C: ''wamp''www''wordpress''wp-content''plugins''post-annalytic-new''Google''Client.php在18号线上当我浏览目录文件时,它在那里,但包含文件有问题。

首先检查命名约定

if是GoogleGoogle文件夹,是Client.php文件或Client.php

如果一切都是正确的,试试这个:

$file = glob(plugin_dir_path(__FILE__)."Google/Client.php";
include_once $file;

如果您使用的是模板,请使用:

get_template_part()

WordPress现在提供了一个函数get_template_part((,它是原生API的一部分,专门用于通过主题重用代码的部分或模板(除了页眉、页脚和侧边栏(。