Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

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
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech
Bacancy logo

Bacancy

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

Bacancy
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
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
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

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

Lucky Media
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

The latest

View all →
Generate Secure, Memorable Passphrases in PHP with PHP Passphrase image

Generate Secure, Memorable Passphrases in PHP with PHP Passphrase

Read article
FrankenPHP v1.11.2 Released With 30% Faster CGO, 40% Faster GC, and Security Patches image

FrankenPHP v1.11.2 Released With 30% Faster CGO, 40% Faster GC, and Security Patches

Read article
Capture Web Page Screenshots in Laravel with Spatie's Laravel Screenshot image

Capture Web Page Screenshots in Laravel with Spatie's Laravel Screenshot

Read article
Nimbus: An In-Browser API Testing Playground for Laravel image

Nimbus: An In-Browser API Testing Playground for Laravel

Read article
Laravel 12.51.0 Adds afterSending Callbacks, Validator whenFails, and MySQL Timeout image

Laravel 12.51.0 Adds afterSending Callbacks, Validator whenFails, and MySQL Timeout

Read article
Handling Large Datasets with Pagination and Cursors in Laravel MongoDB image

Handling Large Datasets with Pagination and Cursors in Laravel MongoDB

Read article