简体   繁体   中英

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

I am integrating google spreadsheet in my project. I have to save form data into google spreadsheet.
For this i am using asimqt php-google-spreadsheet-client library.

I have single form on site that form is submitting using ajax. For this i have written function in function.php.

Getting error when initializing object of DefaultServiceRequest class.

Error: Fatal error: Class 'Google\\Spreadsheet\\DefaultServiceRequest' not found

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 ?

This seems to be an issue with the location of your vendor folder. 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

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 :

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

Just replace require '/vendor/autoload.php'; to require_once('vendor/autoload.php');

Just now I tried this here for you myself and it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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