In the previous tutorial we have learn as how to Install WordPress inside a Laravel application in a subdirectory and same domain and access it using example.com/blog/
. In this tutorial we will be learning as how to access WordPress post
, page
, or any custom post type
data through Laravel.
There are 2 ways to do this
- Through WordPress REST API
- Directly access WordPress database through Laravel Modal
Directly access WordPress database through Laravel Modal
We need to create Modal BlogPost
and BlogPostmeta
to access data from wp_posts
and wp_postmeta
table respectively.
Modal BlogPost.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BlogPost extends Model {
protected $connection = 'wordpress_db_connection';
protected $table = 'posts';
protected $primaryKey = 'ID';
/**
* Get the postmeta for the blog post.
*/
public function postmetas() {
return $this->hasMany('App\BlogPostmeta', 'post_id');
}
/**
* Get comments from the blog post.
*/
public function comments() {
return $this->hasMany('BlogComment', 'comment_post_ID');
}
/**
* Filter by post type
*/
public function scopeType($query, $type = 'post') {
return $query->where('post_type', '=', $type);
}
/**
* Filter by post status
*/
public function scopeStatus($query, $status = 'publish') {
return $query->where('post_status', '=', $status);
}
/**
* Filter by post author
*/
public function scopeAuthor($query, $author = null) {
if (!empty($author)) {
return $query->where('post_author', '=', $author);
}
}
//Method to get post with postmeta
Public function getPosts() {
return BlogPost::with('postmetas')
->status()
->type()
->get();
}
}
Modal BlogPostmeta.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BlogPostmeta extends Model {
protected $connection = 'wordpress_db_connection';
protected $table = 'postmeta';
protected $primaryKey = 'meta_id';
/**
* Get the postmeta for the blog post.
*/
public function post() {
return $this->belongsTo('App\BlogPost');
}
}
Now as we have set the database connection and model last thing that we need is to retrieve post. In controller we have to use our Post model to get post
as use App\BlogPost;
.
public function getPostList() {
$BlogPost = new BlogPost();
$posts = $BlogPost->getPosts();
dd($posts);
}
$posts
will hold all your active published post and under postmetas
key it will be holding all the meta's that are related to that specific post.
In next tutorial we will be digging deep into WP Comments and WP Author.