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.
Guess what, we can already make API calls after installation. No need to configure anything, we just launch the URL in the browser:
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:
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:
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:
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:
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!