Use WordPress backend with Laravel or any PHP application
Use WordPress backend with Laravel or any PHP application
A collection of Model classes that allows you to get data directly from a WordPress database. Corcel is a collection of PHP classes built on top of Eloquent ORM (from Laravel framework), that provides a fluent interface to connect and get data directly from a WordPress database.
You can use WordPress as the backend (administration panel) or CMS, for inserting posts, custom types, etc, and any other PHP app in the other side querying those data (as a Model layer). It's easier to use Corcel with Laravel, but you're free to use it with any PHP project that uses Composer.
Buy me a Coffee | Follow Corcel on Twitter
| Laravel | Corcel |
|---|---|
| 5.1.x | ~2.1.0 |
| 5.2.x | ~2.2.0 |
| 5.3.x | ~2.3.0 |
| 5.4.x | ~2.4.0 |
| 5.5.x | ~2.5.0 |
| 5.6.x | ~2.6.0 |
| 5.7.x | ~2.7.0 |
| 5.8.x | ~2.8.0 |
| 6.0.x | ^3.0.0 |
| 7.0.x | ^4.0.0 |
| 8.0.x | ^5.0.0 |
| 9.0.x | ^6.0.0 |
| 10.0.x | ^7.0.0 |
| 11.0.x | ^8.0.0 |
| 12.0.x | ^9.0.0 |
You need to use Composer to install Corcel into your project:
composer require jgrossi/corcelCorcel wil register itself using Laravel's Auto Discovery.
You'll have to include CorcelServiceProvider in your config/app.php:
'providers' => [
/*
* Package Service Providers...
*/
Corcel\Laravel\CorcelServiceProvider::class,
]Now configure our config file to make sure your database is set correctly and to allow you to register custom post types and shortcodes in a very easy way:
Run the following Artisan command in your terminal:
php artisan vendor:publish --provider="Corcel\Laravel\CorcelServiceProvider"Now you have a config/corcel.php config file, where you can set the database connection with WordPress tables and much more.
Just set the database connection you want to be used by Corcel in config/corcel.php.
Let' suppose you have those following database connections in your config/database.php file:
…In this case you should want to use the wordpress connection for Corcel, so just set it into the Corcel config file config/corcel.php:
'connection' => 'wordpress',Here you have to configure the database to fit the Corcel requirements. First, you should include the Composer autoload file if not already loaded:
require __DIR__ . '/vendor/autoload.php';Now you must set your WordPress database params:
$params = [
'database' => 'database_name',
'username' => 'username',
'password' => 'pa$$word',
'prefix' => 'wp_' // default prefix is 'wp_', you can change to your own prefix
];
Corcel\Database::connect($params);You can specify all Eloquent params, but some are default (but you can override them).
'driver' => 'mysql',
'host' => 'localhost',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => 'wp_', // Specify the prefix for WordPress tables, default prefix is 'wp_'Every time you see
Post::method(), if you're using your own Post class (where you set the connection name), likeApp\Postyou should useApp\Post::method()and notPost::method(). All the examples are assuming you already know this difference.
In the examples, every time you see
Post::method()assumeCorcel\Model\Post::method().
// All published posts
$posts = Post::published()->get();
$posts = Post::status('publish')->get();
// A specific post
$post = Post::find(31);
echo $post->post_title;Optionally you can create your own Post model (or Page, or whatever) which extends Corcel\Post. Then set the connection name (if you want to override the Corcel's default one) you're using, in this case foo-bar:
Extending
Corcel\Model\Postclass can add flexibility to your project, once you can add custom methods and logic, according what you need to use from your WordPress database.
<?php // File: app/Post.php
namespace App;
use Corcel\Model\Post as Corcel;
class Post extends Corcel
{
protected $connection = 'foo-bar';
public function customMethod() {
//
}
}So, now you can fetch WP database data using your own class:
$posts = App\Post::all(); // using the 'foo-bar' connectionJust remember you don't have to extends our
Postclass, you can useCorcel\Model\Postand all others model without any problem.
NOTE: In Corcel v1 you could save meta data using the
Post::save()method. That's not allowed anymore. UsesaveMeta()orcreateMeta()(see below) methods to save post meta.
You can retrieve meta data from posts too.
// Get a custom meta value (like 'link' or whatever) from a post (any type)
$post = Post::find(31);
echo $post->meta->link; // OR
echo $post->fields->link;
echo $post->link; // ORTo create or update meta data form a User just use the saveMeta() or saveField() methods. They return bool like the Eloquent save() method.
$post = Post::find(1);
$post->saveMeta('username', 'jgrossi');You can save many meta data at the same time too:
$post = Post::find(1);
$post->saveMeta([
'username' => 'jgrossi',
'url' => 'http://jgrossi.com',
]);You also have the createMeta() and createField() methods, that work like the saveX() methods, but they are used only for creation and return the PostMeta created instance, instead of bool.
$post = Post::find(1);
$postMeta = $post->createMeta('foo', 'bar'); // instance of PostMeta class
$trueOrFalse = $post->saveMeta('foo', 'baz'); // booleanThere are multiples possibilities to query posts by their custom fields (meta) by using scopes on a Post (or another other model which uses the HasMetaFields trait) class:
To check if a meta key exists, use the hasMeta() scope:
// Finds a published post with a meta flag.
$post = Post::published()->hasMeta('featured_article')->first();If you want to precisely match a meta-field, you can use the hasMeta() scope with a value.
// Find a published post which matches both meta_key and meta_value.
$post = Post::published()->hasMeta('username', 'jgrossi')->first();If you need to match multiple meta-fields, you can also use the hasMeta() scope passing an array as parameter:
$post = Post::hasMeta(['username' => 'jgrossi'])->first();
$post = Post::hasMeta(['username' => 'jgrossi', 'url' => 'jgrossi.com'])->first();
// Or just passing the keys
$post = Post::hasMeta(['username', 'url'])->first();If you need to match a case-insensitive string, or match with wildcards, you can use the hasMetaLike() scope with a value. This uses an SQL LIKE operator, so use '%' as a wildcard operator.
// Will match: 'J Grossi', 'J GROSSI', and 'j grossi'.
$post = Post::published()->hasMetaLike('author', 'J GROSSI')->first();
// Using % as a wildcard will match: 'J Grossi', 'J GROSSI', 'j grossi', 'Junior Grossi' etc.
$post = Post::published()->hasMetaLike('author', 'J%GROSSI')->first();The Post class has support to "aliases", so if you check the Post class you should note some aliases defined in the static $aliases array, like title for post_title and content for post_content.
$post = Post::find(1);
$post->title === $post->post_title; // trueIf you're extending the Post class to create your own class you can use $aliases too. Just add new aliases to that static property inside your own class and it will automatically inherit all aliases from parent Post class:
class A extends \Corcel\Post
{
protected static $aliases = [
'foo' => 'post_foo',
];
}
$a = A::find(1);
echo $a->foo;
echo $a->title; // from Post classTo order posts you can use newest() and oldest() scopes, for both Post and User classes:
$newest = Post::newest()->first();
$oldest = Post::oldest()->first();To order posts just use Eloquent paginate() method:
$posts = Post::published()->paginate(5);
foreach ($posts as $post) {
// ...
}To display the pagination links just call the links() method:
{{ $posts->links() }}If you want to retrieve a custom field created by the Advanced Custom Fields (ACF) plugin, you have to install the corcel/acf plugin - click here for more information - and call the custom field like this:
$post = Post::find(123);
echo $post->acf->some_radio_field;
$repeaterFields = $post->acf->my_repeater_name;To avoid unnecessary SQL queries just set the field type you're requesting. Usually two SQL queries are necessary to get the field type, so if you want to specify it you're skipping those extra queries:
$post = Post::find(123);
echo $post->acf->text('text_field_name');
echo $post->acf->boolean('boolean_field_name');You can work with custom post types too. You can use the type(string) method or create your own class.
// using type() method
$videos = Post::type('video')->status('publish')->get();
// using your own class
class Video extends Corcel\Post
{
protected $postType = 'video';
}
$videos = Video::status('publish')->get();Using type() method will make Corcel to return all objects as Corcel\Post. Using your custom class you have the advantage to customize classes, including custom methods and properties, return all objects as Video, for example.
Custom post types and meta data:
// Get 3 posts with custom post type (store) and show its address
$stores = Post::type('store')->status('publish')->take(3)->get();
foreach ($stores as $store) {
$storeAddress = $store->address; // option 1
$storeAddress = $store->meta->address; // option 2
$storeAddress = $store->fields->address; // option 3
}Every time you call something like Post::type('video)->first() or Video::first() you receive a Corcel\Model\Post instance.
If you choose to create a new class for your custom post type, you can have this class be returned for all instances of that post type.
Instead of call Post::registerPostType() method for all custom post type you want
No open issues yet, or sync has not completed.