简体   繁体   English

如何在wordpress的function.php中的函数内部创建类的对象

[英]How to create object of class inside function in function.php of wordpress

I am integrating google spreadsheet in my project. 我正在将Google电子表格集成到我的项目中。 I have to save form data into google spreadsheet. 我必须将表单数据保存到Google电子表格中。
For this i am using asimqt php-google-spreadsheet-client library. 为此,我正在使用asimqt php-google-spreadsheet-client库。

I have single form on site that form is submitting using ajax. 我在网站上有一个表单,该表单正在使用ajax提交。 For this i have written function in function.php. 为此,我在function.php中编写了函数。

Getting error when initializing object of DefaultServiceRequest class. 初始化DefaultServiceRequest类的对象时出错。

Error: Fatal error: Class 'Google\\Spreadsheet\\DefaultServiceRequest' not found 错误:致命错误:找不到类“ Google \\ Spreadsheet \\ DefaultServiceRequest”

require '/vendor/autoload.php';

use  Google\Spreadsheet\DefaultServiceRequest;
use  Google\Spreadsheet\ServiceRequestFactory;


function spreadsheet_feeds()
{
    $access_tok = 'xyz-token';

    $serviceRequest = new DefaultServiceRequest($access_tok); // Getting error
    ServiceRequestFactory::setInstance($serviceRequest);

    $spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
    $spreadsheetFeed = $spreadsheetService->getSpreadsheets();

}

add_action( 'wp_ajax_nopriv_spreadsheet_data', 'spreadsheet_feeds' );
add_action('wp_ajax_spreadsheet_data','spreadsheet_feeds');

Any help why this error is occurring because class is already include using "use" statement ? 为什么会因为类已经包含使用“ use”语句而发生此错误,这有什么帮助吗?

This seems to be an issue with the location of your vendor folder. 这似乎与您的vendor文件夹的位置有关。 Make sure that the vendor folder is accessible by the file 确保文件可以访问供应商文件夹

Considering your folder hierarchy to be 考虑您的文件夹层次结构是

-wp-content
--themes
---your-theme
----functions.php

If you have your vendor folder in your-theme/vendor then in your functions.php 如果your-theme/vendor有供应商文件夹,则在functions.php中

you should write 你应该写

require 'vendor/autoload.php';

and if vendor is in the root directory of WP make sure you traverse back to the root folder using something like : 并且如果vendor位于WP的根目录中,请确保使用以下命令遍历到根文件夹:

require __DIR__ .'/../../../../vendor/autoload.php';

Just replace require '/vendor/autoload.php'; 只需替换require '/vendor/autoload.php'; to require_once('vendor/autoload.php'); require_once('vendor/autoload.php');

Just now I tried this here for you myself and it works. 刚才我在这里为您自己尝试过,并且有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM