This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Calculate Your Savings on Cloudways and Compare With Kinsta, WP Engine and Flywheel. Calculate Now

Integrating Laravel and WordPress: How to Streamline Content Transferring From Google Docs in Few Minutes

Updated on December 10, 2021

8 Min Read
laravel wordpress

Google Docs are widely used to write, edit and share documents online. It allows easy access to important documents from anywhere anytime. It is one of those first word processors that introduced online document editing, providing ease to the teams to enhance their work process and collaboration for projects.

Many bloggers, editors and journalists use Google Doc and WordPress to write and publish their content. But, all of them tend to face one common issue i.e how to export / transfer content directly from Google Doc to WordPress instead of copy/pasting it.

So integrating Laravel with WordPress, we will develop an application here that exports content directly from Google Doc to WordPress. To begin with, we will build an application on Laravel to integrate Google Doc API with WordPress. The API will be used to get a document from Google Doc and post it to WordPress as a blog/post.

Nothing as Easy as Deploying Laravel Apps on Cloud

With Cloudways, you can run your PHP apps on managed cloud servers in just a few minutes.

Prerequisites

To get the best out of this Laravel and WordPress integration, you need to set up both of these applications on Cloudways. The platform provides an industry-leading Laravel hosting solution built on an amazing stack of tools, including Varnish, Redis, Memcache, and other features.

Then, install a basic authentication plugin for WordPress and a Guzzlehttp package and Google API package for your Laravel application. 

Integrating Laravel to Google Doc API

Sign up with Google API

To integrate a Laravel application, sign in to your Google account first. Then, navigate to the Google Developers Console and create or select an existing project.

Now click ‘Continue’ and go to the credentials.

Choose Google drive API, select Web Server and check User Data.

Enter client ID name and enter Laravel route as redirect URLs. Enter your domain name instead of localhost address for production. Redirect URL will be used to redirect users back to your app after authentication. Create client ID and enter product name. Then, download JSON credentials file and save it.

Now, click on Enable API and Services from the dashboard.

Now, search for Google Drive and Google+ APIs and make sure both are enabled.

Next, install the Google API package.

composer require google/apiclient

CONFIGURE GOOGLE SERVICE

GOOGLE_APP_ID=

GOOGLE_CLIENT_ID=

GOOGLE_CLIENT_SECRET=

GOOGLE_REDIRECT_URL=

GOOGLE_SCOPES="https://www.googleapis.com/auth/drive.readonly"

GOOGLE_APPROVAL_PROMPT="force"

GOOGLE_ACCESS_TYPE="offline"

Add these credentials to your .env file and add your APP_ID,CLIENT_ID,CLIENT_SECRET,REDIRECT_URL to your own credentials from the JSON file you have downloaded earlier.

Here, we are using the https://www.googleapis.com/auth/drive.readonly as a scope to get permission for reading Google Drive contents.

Now, create a Google class as App\Google.php:

<?php

namespace App;

class Google

{

    public function client()

    {

        $client = new \Google_Client();

        $client->setClientId(env('GOOGLE_CLIENT_ID'));

        $client->setClientSecret(env('GOOGLE_CLIENT_SECRET'));

        $client->setRedirectUri(env('GOOGLE_REDIRECT_URL'));

        $client->setScopes(explode(',', env('GOOGLE_SCOPES')));

        $client->setApprovalPrompt(env('GOOGLE_APPROVAL_PROMPT'));

        $client->setAccessType(env('GOOGLE_ACCESS_TYPE'));



        return $client;

    }

    public function doc($client)

    {

        $doc = new \Google_Service_Docs($client);

        return $doc;

    }

    public function drive($client)

    {

        $drive = new \Google_Service_Drive($client);

        return $drive;

    }

    public function service($client)

    {

        $service = new \Google_Service_Books($client);

        return $service;

    }

}

The code above establishes a connection with the Google client by passing the credentials from your .env file to the class. To get the Google Drive service, you have to pass in the client function which is also the credentials of the \Google_service_drive. It helps you to access files from your Google Drive and edit them as per the requirements. Likewise for the doc function which enable you to access the content of your documents file and allows you to change it as per needs.

Let’s get started with the Laravel core. First of all, we will create our controllers as defined below:

  • php artisan make:controller AuthController;
  • php artisan make:controller GoogleController;

The Authcontroller will handle our auth0 authentication and redirection, while the GoogleController will handle getting document content from drive API and posting it to WordPress API.

Let’s create our route from the routes\web.php:

Route::get('/login/google', '[email protected]');

Route::get('/login/google/callback', '[email protected]');

Route::get('/post/blog', '[email protected]');

The /login/google/callback route is the redirect URL used when setting up a Google API.

Let’s start with the AuthController:

<?php

namespace App\Http\Controllers;

use App\Google;

use Illuminate\Http\Request;



class AuthController extends Controller

{

    //

    public function index(){

    return view('home');

    }

    public function __construct(Google $google, Request $request)

    {

        $this->client = $google->client();

        $this->drive = $google->drive($this->client);

    }

    public function redirectToGoogleProvider(GoogleDoc $googleDoc)

    {

        $client = $googleDoc->client();

        $auth_url = $client->createAuthUrl();

        return redirect($auth_url);

    }

    public function handleProviderGoogleCallback(Request $request)

    {

        if($request->has('code')){

            $client = $this->client;

            $client->authenticate($request->input('code'));

            $token = $client->getAccessToken();

            $request->session()->put('access_token',$token);

           return redirect('/home')->with('success','you have been authenticated');

        }else{

            $client=$googleDoc->client();

            $auth_url = $client->createAuthUrl();

            return redirect($auth_url);

        }

    }

}

The ToGoogleProvider() method requests for the user permission to manage the Drive data i.e by requesting the actual Google account.

The handleProviderGoogleCallback() method allows us to get the token which has been passed from the redirectToGoogleProvider() method. We can also use this method in sessions as access_token, to reduce repetitive actions for sending a request to the Google Drive API.

Before proceeding to our GoogleController which will handle our integration, we will first configure WordPress.

Configuring WordPress

As defined above in the prerequisites, we have already configured WordPress, and now we will download and install basic authentication plugin which will handle our authentication process.

Note: This plugin requires sending your username and password with every request, and should only be used for development and testing purposes i.e. not in a production environment. Other plugins like JSON Web Tokens etc can be used in production.

Coming back to our Laravel application, we need to install the Guzzlehttp package, which is quite handy for working with HTTP requests. A PHP HTTP client makes it easy to send and receive HTTP requests to integrate with web services.

Improve Your Laravel App Speed by 300%

Cloudways offers you dedicated servers with SSD storage, custom performance, an optimized stack, and more for 300% faster load times.

Installing Guzzle

composer require guzzlehttp/guzzle:~6.0

Paste the following code to GoogleController:

GoogleController

<?php

namespace App\Http\Controllers;

use App\Google;

use GuzzleHttp\Client;

use Illuminate\Http\Request;

class GoogleController extends Controller

{

public function __construct(Google $google, Request $request)

{

    $this->client = $google->client();

    $this->drive = $google->drive($this->client);

}

public function handlePost(Request $request)

{

global $image_url;

if ($request->session()->get('access_token')){

    $client=$this->client;

    $client->setAccessToken($request->session()->get('access_token'));

//getting document from drive that contain 'blog'

            $pageToken = NULL;

            $optParams = [

                    'q'=>"name contains 'blog'",

                    'spaces'=>"drive",

                    'fields' =>"nextPageToken, files(id, name)",

                    'pageToken'=>$pageToken

            ];

            $respon = $this->drive->files->listFiles($optParams)->getFiles();

            foreach ($respon as $respons) {

                //getting the content of the documents

                $file = new \Google_Service_Docs($client);

                $document = $respons['id'];



                $doc = $file->documents->get($document);

                $contents = $doc->getBody()->getContent();

                $datas = [];

                for ($i = 0; $i < count($contents); $i++) {

                    if ($contents[$i]->getParagraph() == null) {

                        continue;

                    }

                    $table = $contents[$i]->getParagraph()->getElements();

                    for ($j = 0; $j < count($table); $j++) {

                        if ($table[$j]->getTextRun() == null) {

                            goto image;

                        }

                        $cell = $table[$j]->getTextRun()->getContent();

                        array_push($datas, $cell);

                        image:

                        if ($table[$j]->getInlineObjectElement() == null) {

                            continue;

                        }

                        $image_id = $table[$j]->getInlineObjectElement()->getInlineObjectId();

                        $url = $doc->getInlineObjects();



                        $image_url2 = "<img " . "src" . "=" . $url[$image_id]->getInlineObjectProperties()->getEmbeddedObject()->getImageProperties()->contentUri . ">";

                        array_push($datas, $image_url2);

                        $image_url = $url[$image_id]->getInlineObjectProperties()->getEmbeddedObject()->getImageProperties()->contentUri;

                    }

                }

//connection to wordpress api

                $username = 'admin';

                $password = 'admin';

                $client = new Client([

                    'base_uri' => 'http://localhost:8888/wordpress/wp-json/wp/v2/',

                    'headers' => [

                        'Authorization' => 'Basic ' . base64_encode($username . ':' . $password),

                        'Accept' => 'application/json',

                        'Content-type' => 'application/json',

                        'Content-Disposition' => 'attachment',

                    ]

                ]);



                // uploading featured image to wordpress media and getting id

                $name = $doc->getTitle() . '.' . 'jpg';

                $responses = $client->post(

                    'media',

                    [

                        'multipart' => [

                            [

                                'name' => 'file',

                                'contents' => file_get_contents($image_url),

                                'filename' => $name

                            ],

                        ]

                    ]);

                $image_id_wp = json_decode($responses->getBody(), true);

// uploading post to wordpress with featured image id

                $response = $client->post('posts', [

                    'multipart' => [

                        [

                            'name' => 'title',

                            'contents' => $doc->getTitle()

                        ],

                        [

                            'name' => 'content',

                            'contents' => implode("", $datas)

                        ],

                        [

                            'name' => 'featured_media',

                            'contents' => $image_id_wp['id']

                        ],

                    ]

                ]);            

            }

    return redirect('/home')->with('success','post has been created');

}else{

   return redirect('/home')->with('error','you have not been authenticated');

}

}

}

The first thing is to get the access_token being put in session. Then, we will get our documents ID from Google Drive by passing the $optParams[] to the  listfiles() method. The $optParams[] specifies the type of file and directory we are trying to access, which in our case is any file that has ‘blog’ as part of its name in the root directory.

Note: You have to include ‘blog’ as part of the name on each document you are posting. You can still change the values of the $optParams[].

$pageToken = NULL;

            $optParams = [

                    'q'=>"name contains 'blog'",

                    'spaces'=>"drive",

                    'fields' =>"nextPageToken, files(id, name)",

                    'pageToken'=>$pageToken

            ];

            $respon = $this->drive->files->listFiles($optParams)->getFiles();

The next step is to loop through all the documents and getting their contents by passing the document ID to the get() method in the Google_service_Docs class.

Getting Content of the Document

The getContent() method being called from the getBody() method, displays the content of the document in an array i.e each line in your document is considered as an index of the getContent().

Looping through the getContent() array, we will get the getElements() method which is also an array().

Looping through the getElements() will let us access the getTextRun()->getContent() that displays the value of the first paragraph in your document.

We will also try to get images ID from the document by using the getInlineObjectElement() method from the getParagraph()->getElements() method. Then, we will pass the imageID as an index to the $doc->getInlineObjects() method to get the URL of the image.

Each line in your document is then pushed to the $data array, so that the content will look exactly the same as in the original document.

$file = new \Google_Service_Docs($client);

                $document = $respons['id'];

                $doc = $file->documents->get($document);

                $contents = $doc->getBody()->getContent();

                $datas = [];

                for ($i = 0; $i < count($contents); $i++) {

                    if ($contents[$i]->getParagraph() == null) {

                        continue;

                    }

                    $table = $contents[$i]->getParagraph()->getElements();

                    for ($j = 0; $j < count($table); $j++) {

                        if ($table[$j]->getTextRun() == null) {

                            goto image;

                        }

                        $cell = $table[$j]->getTextRun()->getContent();

                        array_push($datas, $cell);

                        image:

                        if ($table[$j]->getInlineObjectElement() == null) {

                            continue;

                        }

                        $image_id = $table[$j]->getInlineObjectElement()->getInlineObjectId();

                        $url = $doc->getInlineObjects();

                        $image_url2 = "<img " . "src" . "=" . $url[$image_id]->getInlineObjectProperties()->getEmbeddedObject()->getImageProperties()->contentUri . ">";

                        array_push($datas, $image_url2);

                        $image_url = $url[$image_id]->getInlineObjectProperties()->getEmbeddedObject()->getImageProperties()->contentUri;

                    }

                }

Connecting to WordPress API

Now, using the guzzlehttp package, we will setup the WordPress API URL authorization by passing the header array[], which will use our WordPress username and password encoded in base64.

//connection to wordpress api

                $username = 'admin';

                $password = 'admin';

                $client = new Client([

                    'base_uri' => 'http://localhost:8888/wordpress/wp-json/wp/v2/',

                    'headers' => [

                        'Authorization' => 'Basic ' . base64_encode($username . ':' . $password),

                        'Accept' => 'application/json',

                        'Content-type' => 'application/json',

                        'Content-Disposition' => 'attachment',

                    ]

                ]);

Uploading the post’s featured image

Each WordPress post has a featured image that displays on the homepage. We will upload the featured image to our WordPress media using the WordPress API endpoint for the media.

Note: Based on this article, the last image on your document will be the featured image for the WordPress post.

Then, we will pass the $image_url variable being declared as global, to the file_get_contents method as the content of the post. Also the filename must be specified, having some image extension (jpg,png etc.).

// uploading featured image to wordpress media and getting id

                $name = $doc->getTitle() . '.' . 'jpg';

                $responses = $client->post(

                    'media',

                    [

                        'multipart' => [

                          [

                           'name' => 'file',

                           'contents' => file_get_contents($image_url),

                           'filename' => $name

                          ],

                        ]

                    ]);

                $image_id_wp = json_decode($responses->getBody(), true);

It will return a JSON response, so that we can get the featured image ID and pass it together with the post.

Uploading your Post to WordPress

Finally, we will now upload our word document as a post in WordPress. We will pass the name of the document as the title of the post with the $getTitle() method.

The content of the post will be the document that is being pushed to the $data[]. But we will have to pass in the $data[] to the implode(), so as to convert it into a variable before uploading it to the post.

The featured image will be the featured image ID we got from the JSON response after uploading the image to the WordPress media.

// uploading post to wordpress with featured image id

                $response = $client->post('posts', [

                    'multipart' => [

                        [

                           'name' => 'title',

                           'contents' => $doc->getTitle()

                        ],

                        [

                           'name' => 'content',

                           'contents' => implode("", $datas)

                        ],

                        [

                           'name' => 'featured_media',

                           'contents' => $image_id_wp['id']

                        ],

                    ]

                ]);

Final Words

This brings us to the end of this article, which demonstrated in detail how to integrate Google Docs with WordPress using Laravel framework. Being a blogger or a content writer, it often seems quite tedious to manually copy and paste all the content from Google Docs to WordPress. It takes time, requires extra effort and sometimes gets mistaken for the actual content of the document.

That is why, this Laravel and WordPress integration article is meant for all those individuals who want to streamline their publishing work. It makes writing and publishing process super easy and hassle free.

If you still have some queries or want to add your suggestions to this article, please feel free to write them in the comment section below.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Customer Review at

“Cloudways hosting has one of the best customer service and hosting speed”

Sanjit C [Website Developer]

Olususi k Oluyemi

A tech enthusiast, programming freak and a web development junkie who loves to embrace new technology.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Unleash The Cloud.
Not Budgets.

For 4 Months +
Up To 30 Free Migrations

Cyber Week

SAVINGS
Time Left In Offer
  • 0

    Days

  • 0

    Hours

  • 0

    Minutes

  • 0

    Seconds

40% OFF

On All Plans

GET THE DEAL NOW