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.

image
DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

Visit DocuWriter.ai
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
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
LoadForge logo

LoadForge

Easy, affordable load testing and stress tests for websites, APIs and databases.

LoadForge
Paragraph logo

Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Paragraph
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

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
Bacancy - Staff Augmentation logo

Bacancy - Staff Augmentation

Leave your web app development hustles to the leading IT Staff Augmentation Service Providers. Choose from an extensive pool of 1050+ developers and give yourself the sigh of success you deserve with Bacancy. Get In Touch Today!

Bacancy - Staff Augmentation
DocuWriter.ai logo

DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

DocuWriter.ai
Rector logo

Rector

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

Rector

The latest

View all →
Add Kanban Boards to Your Laravel App in Seconds image

Add Kanban Boards to Your Laravel App in Seconds

Read article
October CMS v3.6 Ships Today, Full of New Features image

October CMS v3.6 Ships Today, Full of New Features

Read article
Laracon EU Videos are now out image

Laracon EU Videos are now out

Read article
Use Google's Gemini AI in Laravel image

Use Google's Gemini AI in Laravel

Read article
PhpStorm is getting a brand new terminal image

PhpStorm is getting a brand new terminal

Read article
Six Essential Plugins for Visual Studio Code image

Six Essential Plugins for Visual Studio Code

Read article