Laravel Wordpress REST API Tutorial Example

By Hardik Savani April 16, 2024 Category : Laravel

Hey Guys,

I am going to show you an example of laravel wordpress rest api. I explained simply step by step how to call wordpress rest api in laravel. if you want to see an example of laravel call wordpress rest api example then you are in the right place. you will learn laravel wordpress create post api example.

In this illustration, our objective is to retrieve WordPress posts through the WordPress REST API and construct a form for generating posts on a WordPress website via the REST API. We will employ the /wp-json/wp/v2/posts API, utilizing both the GET and POST methods to retrieve and create posts. To achieve this, let's proceed with a series of steps in this example.

You can call wordpress rest api in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

Preview:

Step 1: Install Laravel

This step is optional. Nevertheless, if you haven't yet created the Laravel app, you can proceed by running the following command:

composer create-project laravel/laravel example-app

Step 2: Wordpress Configuration

In this step, we will configure wordpress website and generate username and password.

first go to your wordpress website admin panel as with following url:

"URL + /wp-admin"

Next, go to users list page with following url, then copy username and click on it:

"URL + /wp-admin/users.php"

Next, you need to generate new password to click on "New Application Password" button.

This is optional, you can go on "Settings > Permalinks" to set "Permalink structure" to "Post name" as shown in following screenshot:

Now, let's add Site URL, Username and Password in .env file as like the below:

.env

WP_SITE=https://wp.demo.com

WP_USERNAME=root

WP_PASSWORD=8M1L3q9Uzqo4GLbmOT

Step 3: Create Controller

In this step, we will create PostController with index() and store() method. so let's create controller using bellow command.

php artisan make:controller PostController

Now, update the code on the controller file.

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Http;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$response = Http::withBasicAuth(env('WP_USERNAME'), env('WP_PASSWORD'))

->withOptions([

'verify' => false,

])->get(env('WP_SITE').'/wp-json/wp/v2/posts');

$posts = $response->json();

return view('posts', compact('posts'));

}

/**

* Write code on Method

*

* @return response()

*/

public function store(Request $request)

{

$this->validate($request, [

'title' => 'required',

'body' => 'required'

]);

$parameters = [

'title' => $request->title,

'content' => $request->body,

'status' => 'publish',

];

$response = Http::withBasicAuth(env('WP_USERNAME'), env('WP_PASSWORD'))

->withOptions([

'verify' => false,

])->post(env('WP_SITE').'/wp-json/wp/v2/posts', $parameters);

return to_route('posts.index')

->with('success', 'Post created successfully.');

}

}

Step 4: Add Route

Furthermore, open routes/web.php file and update code on it.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\PostController;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!

|

*/

Route::get('posts',[PostController::class,'index'])->name('posts.index');

Route::post('posts/store',[PostController::class,'store'])->name('posts.store');

Step 5: Create View File

In Last step, let's create posts.blade.php(resources/views/posts.blade.php) for display all wordpress post and create new post form:

resources/views/posts.blade.php

<!DOCTYPE html>

<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>

<meta name="csrf-token" content="{{ csrf_token() }}">

<title>Laravel Wordpress REST API Example - ItSolutionStuff.com</title>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css">

</head>

<body>

<div class="container mt-5" style="max-width: 750px">

<h1>Laravel Wordpress REST API Example - ItSolutionStuff.com</h1>

@if ($message = Session::get('success'))

<div class="alert alert-success alert-dismissible">

<button type="button" class="close" data-dismiss="alert">×</button>

<strong>{{ $message }}</strong>

</div>

@endif

<form method="post" action="{{ route('posts.store') }}" enctype="multipart/form-data">

@csrf

<div class="form-group">

<label>Title</label>

<input type="text" name="title" class="form-control" />

</div>

<div class="form-group">

<label>Description</label>

<textarea id="summernote" class="form-control" name="body"></textarea>

</div>

<div class="form-group mt-3 mb-3">

<button type="submit" class="btn btn-success btn-block">Publish</button>

</div>

</form>

<div id="data-wrapper">

@foreach ($posts as $post)

<div class="card mb-2">

<div class="card-body">

<h5 class="card-title">{{ $post['title']['rendered'] }}</h5>

{!! Str::limit(strip_tags($post['content']['rendered']), 200) !!}

<br/>

<a href="{{ $post['link'] }}">View</a>

</div>

</div>

@endforeach

</div>

</div>

</body>

</html>

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/posts

Wordpress Posts:

Laravel Page:

Now we are ready to run this example and check it...

I hope it can help you...

Tags :
Shares