skip to Main Content

Laravel 5 Get Recent Posts WordPress Using REST API

Laravel 5 get recent posts WordPress using REST API


WordPress is the popular CMS so basically we are creating our blog on WordPress. I am working on Laravel project and client want to use WordPress for blogging. Now, Client wants to display recent WordPress posts on Laravel sidebar. I going to share with you How to Laravel 5 get recent posts WordPress using API.

We are using the CURL for fetching the WordPress recent post using REST API. We are using Laravel Ixudra package for sending CURL request.

I hope you install Laravel If not please follow tutorial. This article for installing Ixudra package.

First of all, We are going to create the “WordPressController”

php artisan make:controller WordPressController

Now, let’s create the route for getting the posts from WordPress using REST API.

Route::get('wordpress/post','WordpressController@getPosts');

Laravel 5 get recent posts WordPress REST API

We are going to write code for fetching the recent posts from WordPress using REST API.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Ixudra\Curl\Facades\Curl;

class WordPressController extends Controller
{

    public function getPosts(){

        $response = Curl::to('https://thecodingstuff.com/wp-json/wp/v2/posts')
        ->withData(['per_page' => 10, 'orderby' => 'date', 'order' => 'desc'])
        ->asJson()
        ->get();

        return view('wordpress_post',['wpposts' => $response]);
    }

}

WordPress REST API allow to fetching posts using “wp-json/wp/v2/posts” on JSON format. For more detail about WordPress REST API.

Let’s create the view file at “resources/views/wordpress_post.blade.php” file print the recent posts

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <ul class="list-group">
                    @foreach( $wpposts as $p_key => $p_value )
                        <li class="list-group-item"> 
                            <a href="{{ $p_value->link }}">
                                {{ $p_value->title->rendered }}
                            </a>
                        </li>
                    @endforeach
                </ul>
            </div>
        </div>
    </div>
@endsection

Our Code is ready If you face any issue for fetching the Posts from WordPress write the comment below

Saroj

I am a web designer and developer part-time blogger. Write something on some free time. Find my every day thought here :)

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top