How to use WordPress as a backend for a Laravel Application

Published on by

How to use WordPress as a backend for a Laravel Application image

Last week I relaunched Laravel News, and the new site is running on Laravel with WordPress as the backend. I’ve been using WordPress for the past two years, and I’ve grown to enjoy the features that it provides. The publishing experience, the media manager, the mobile app, and Jetpack for tracking stats.

I wasn’t ready to give these features up, and I didn’t have the time to build my own system, so I decided to keep WordPress and just use an API plugin to pull all the content I needed out, then store it in my Laravel application. In this tutorial, I wanted to outline how I set it all up.

Please keep in mind there are several different ways of doing this, and you can take a look at the WordPress and Laravel post for a list of third party packages and resources that others have created to solve this same task. The primary options are to either hook into the WordPress database, pull from the API, or sync data from one system to the other.

I choose the sync option because I wanted everything separated. While researching I came across a package called WordPressToLaravel that does this, however, it only works with the wordpress.com hosted sites.

I decided to create my own system for working with a self-hosted WordPress install. This method requires more work up front, but it allows my site to be a typical Laravel application that I can easily improve and extend as needed.

Once I had it syncing content, I then set it up as a recurring task through the Laravel Scheduler, so it’s completely automated.

My setup is also entirely custom for my needs. I only wanted to pull posts, categories, and tags. Pages and other sections are all driven by either static Blade files or other API’s.

Let’s go through how this all works.

WordPress API

WordPress doesn’t ship with an API; however, the community has built a plugin named WP Rest API that allows any blog to have a jSON API.

In my case, I’m doing read-only requests that do not require any authentication. That makes reading and fetching data easy and simplifies a lot of code.

Here is my basic class to fetch a list of posts:

class WpApi
{
protected $url = 'http://site.com/wp-json/wp/v2/';
 
public function importPosts($page = 1)
{
$posts = collect($this->getJson($this->url . 'posts/?_embed&filter[orderby]=modified&page=' . $page));
foreach ($posts as $post) {
$this->syncPost($post);
}
}
 
protected function getJson($url)
{
$response = file_get_contents($url, false);
return json_decode( $response );
}
}

Now when you call WpAPI->importPosts() it will grab the first page of results. The query string is worth mentioning because it has a few special clauses. The first is _embed which will embed all the extra data like image embeds, categories, and tags. Next is a filter to order by last modified that way when you edit a post on WordPress it is then on the first page of results, meaning it’s resynced.

Next, we need the ability to sync the post with our database. Here is how I set it up:

protected function syncPost($data)
{
$found = Post::where('wp_id', $data->id)->first();
 
if (! $found) {
return $this->createPost($data);
}
 
if ($found and $found->updated_at->format("Y-m-d H:i:s") < $this->carbonDate($data->modified)->format("Y-m-d H:i:s")) {
return $this->updatePost($found, $data);
}
}
 
protected function carbonDate($date)
{
return Carbon::parse($date);
}

For this step, I added a wp_id field to my own Posts table that way I have a one to one between my local database and WordPress.

Next, I just check and see if it doesn’t exist, then create it. Otherwise, update it, if it’s been modified since it was originally synced.

The createPost and updatePost are typical Laravel Eloquent inserts or updates. Here is the code for create:

protected function createPost($data)
{
$post = new Post();
$post->id = $data->id;
$post->wp_id = $data->id;
$post->user_id = $this->getAuthor($data->_embedded->author);
$post->title = $data->title->rendered;
$post->slug = $data->slug;
$post->featured_image = $this->featuredImage($data->_embedded);
$post->featured = ($data->sticky) ? 1 : null;
$post->excerpt = $data->excerpt->rendered;
$post->content = $data->content->rendered;
$post->format = $data->format;
$post->status = 'publish';
$post->publishes_at = $this->carbonDate($data->date);
$post->created_at = $this->carbonDate($data->date);
$post->updated_at = $this->carbonDate($data->modified);
$post->category_id = $this->getCategory($data->_embedded->{"wp:term"});
$post->save();
$this->syncTags($post, $data->_embedded->{"wp:term"});
return $post;
}

If you look carefully, there are a few special cases like the author, featured image, category, and tags. Those come from the _embed in the original query string and syncing that data is just a matter of doing the same thing as previous.

public function featuredImage($data)
{
if (property_exists($data, "wp:featuredmedia")) {
$data = head($data->{"wp:featuredmedia"});
if (isset($data->source_url)) {
return $data->source_url;
}
}
return null;
}
 
public function getCategory($data)
{
$category = collect($data)->collapse()->where('taxonomy', 'category')->first();
$found = Category::where('wp_id', $category->id)->first();
if ($found) {
return $found->id;
}
$cat = new Category();
$cat->id = $category->id;
$cat->wp_id = $category->id;
$cat->name = $category->name;
$cat->slug = $category->slug;
$cat->description = '';
$cat->save();
return $cat->id;
}
 
private function syncTags(Post $post, $tags)
{
$tags = collect($tags)->collapse()->where('taxonomy', 'post_tag')->pluck('name')->toArray();
if (count($tags) > 0) {
$post->setTags($tags);
}
}

For the category I am pulling out the first category the post is assigned to because I only want one post per category, then in syncTags, I’m utilizing the Tags package by Cartalyst.

Creating a Scheduled Command

The final step to complete the import is to build a scheduled task to automatically pull posts down. I created a command named Importer through Artisan:

php artisan make:console Importer

Then in the handle method:

$page = ($this->argument('page')) ? $this->argument('page') : 1;
$this->wpApi->importPosts($page);

Finally, in Console/Kernel set this to run every minute:

$schedule->command('import:wordpress')
->everyMinute();

Now every minute of every day it attempts to sync the data and either create, update, or ignore the posts.

Going Further

This is a basic outline in how I set this feature up, and it only scratches the surface on what all could be done. For example, I’m heavily caching all the DB queries within the site and during this sync process if something is updated then the related cache is cleared.

I hope this helps show you that utilizing WordPress as a backend is not that hard to manage and at the same time gives you tons of benefits like creating posts from mobile, using it’s media manager, and even writing in Markdown with Jetpack.

Eric L. Barnes photo

Eric is the creator of Laravel News and has been covering Laravel since 2012.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Laravel Idea for PhpStorm logo

Laravel Idea for PhpStorm

Ultimate PhpStorm plugin for Laravel developers, delivering lightning-fast code completion, intelligent navigation, and powerful generation tools to supercharge productivity.

Laravel Idea for PhpStorm
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
JetShip - Laravel Starter Kit logo

JetShip - Laravel Starter Kit

A Laravel SaaS Boilerplate and a starter kit built on the TALL stack. It includes authentication, payments, admin panels, and more. Launch scalable apps fast with clean code, seamless deployment, and custom branding.

JetShip - Laravel Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Handling Geospatial Data with Laravel Magellan image

Handling Geospatial Data with Laravel Magellan

Read article
Managing Large Datasets in Laravel with LazyCollection image

Managing Large Datasets in Laravel with LazyCollection

Read article
Collect and Monitor Everything About Sent Emails in Your Laravel App image

Collect and Monitor Everything About Sent Emails in Your Laravel App

Read article
Packagist.org is ending support for Composer 1.x image

Packagist.org is ending support for Composer 1.x

Read article
Mastering Dynamic String Manipulation with Laravel's Str::replaceArray() image

Mastering Dynamic String Manipulation with Laravel's Str::replaceArray()

Read article
Laravel Jobs - December image

Laravel Jobs - December

Read article