Wordpress ORM provide an easy way to interact with WordPress database, query, insert and update posts. The syntax is heavily inspired by Eloquent ORM and Laravel.
The package provide two kind of models: Model
to interact with custom table in WordPress and Wodel
to interact with WP_Query in a more natural way ( and it also works well with ACF).
This package only use WP builtin function like WP_Query
, wp_insert_post
and wpdb
.
Via Composer
$ composer require quentingab/wordpress-orm
$posts = \QuentinGab\WordpressOrm\Wodel::init()->type('post')->all();
foreach($posts as $post){
echo $post->post_title;
}
$post = \QuentinGab\WordpressOrm\Wodel::init()->current();
$post = \QuentinGab\WordpressOrm\Wodel::init()->current();
$post->post_title = "Hello World";
$post->save();
$post = new \QuentinGab\WordpressOrm\Wodel(
[
'post_title'=>'Hello World',
'acf' => [
'field_name' => 'value'
]
]
);
$post->save();
class Page extends \QuentinGab\WordpressOrm\Wodel
{
protected $post_type = 'page';
//only necessary if you want to insert a new post programmatically
//otherwise the acf fields will not be populated
//If you only get Wodel or update existing Wodel you can omit $acf_keys
protected $acf_keys = [
'the_field_name' => 'the_field_key',
'color' => 'field_5f7848684c404',
];
}
$page = Page::init()->find(1);
echo $page->acf['color'];
if you have data stored in a custom table you can use \QuentinGab\WordpressOrm\Model to interact with the database. Under the hood it only use default WordPress object $wpdb.
global $wpdb;
$table_name = 'events';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id bigint(20) NOT NULL AUTO_INCREMENT,
title varchar(255),
active boolean DEFAULT 0 NOT NULL,
created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
dbDelta($sql);
class Event extends \QuentinGab\WordpressOrm\Model
{
protected $table = 'events';
protected $primary_key = "id";
protected $fillable = [
'title'
];
protected $casts = [
'active' => 'bool',
'created_at' => "date"
];
}
$all = Event::init()->all();
$only_active = Event::init()->where(['active'=>true])->get();
$with_primary_key_1 = Event::init()->find(1);
$new_event = new Event(['title'=>'my new event','active'=>false]);
$new_event->save();
Please see CHANGELOG for more information on what has changed recently.
$ composer test
Please see CONTRIBUTING and CODE_OF_CONDUCT for details.
If you discover any security related issues, please email quentin.gabriele@gmail.com instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.