wordpress logo

Using WordPress REST API in Laravel

Recent WordPress 4.7 version was released with a huge thing called REST API – earlier it was possible only with external plugins. So now we can query WordPress database from external projects. Including Laravel. So let’s try it out.

I’ve set up a local WordPress website, and after installation I got that usual dashboard.

wordpress local dashboard laravel

Guess what, we can already make API calls after installation. No need to configure anything, we just launch the URL in the browser:

wordpress json laravel

In this case we’ve received a JSON with a list of posts – by default, WordPress creates one dummy post.
Basically, URL structure for the API calls is simple:
/wp-json/wp/v2/[endpoint]?[parameters]

Yes, you’ve read it right, we can get posts, categories, tags and other things that are publicly available, so we don’t need any authentication here.

And we also can filter the data with GET parameters, like this:
/wp-json/wp/v2/posts?per_page=2&orderby=title

Now, let’s try to make an API call from Laravel. For that I will install fresh Laravel 5.4 project which will look like this:

laravel homepage

Now, let’s make the API request to load all the posts from our WordPress installation.
To do that, I will use simple jQuery, but feel free to use Vue or even Angular.

So, we open /resources/views/welcome.blade.php, remove styling, create one empty div and have this:

Of course, it will show empty page with “Loading posts…” at the moment. So let’s add our JavaScript before </body>.

And here’s a quick video with the result.

So it’s quite easy to use WordPress REST API. Of course, you can go deeper and explore much more possibilities than just getting the posts, here’s official Developer Reference for you.

Also worth noting that Eric Barnes published a tutorial on how he used WordPress API for rebuilding his Laravel News website, but it was done half-year ago, before the official WordPress API, with help of plugins.

So, let’s not fight between Laravel and WordPress, we can actually work together, guys!

Want to generate Laravel adminpanel online?
You don't need any packages to do that!

5 thoughts on “Using WordPress REST API in Laravel

  1. Hi, recently appear a bug in the 2.7.1 WordPress version, exactly in the Api Rest feature.
    Is the post still valid and secured?

    Regards

  2. I recently built a site using the threesquared/laravel-wp-api package. Very easy to use and performs much faster than the WordPress site that it uses for it’s endpoint.

Leave a Reply

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