quentingab/wodel

This package is abandoned and no longer maintained. No replacement package was suggested.

WordPress Post Model

v2.1 2021-07-08 11:05 UTC

README

Easy way to interact with WordPress database, query, insert and update posts. And it also works with ACF.

Latest Version on Packagist Software License Total Downloads

Install

Via Composer

$ composer require quentingab/wodel

Usage with WordPress posts

Get all posts/page and custom post type

$posts = QuentinGgab\Models\Wodel::all();
foreach($posts as $post){
    echo $post->post_title;
}

Get current post with acf

$post = QuentinGab\Models\Wodel::current();

Update a post

$post = QuentinGab\Models\Wodel::current();
$post->post_title = "Hello World";
$post->save();

Insert a post

$post = new QuentinGab\Models\Wodel(
    [
    'post_title'=>'Hello World'
    ]
);
$post->save();

Extend the Wodel

class Page extends QuentinGab\Wodel\Models\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 Model or update existing Model you can omit $acf_keys
    protected $acf_keys = [
        'the_field_name' => 'the_field_key',
        'color' => 'field_5f7848684c404',
    ];
}

$page = Page::find(1);
echo $page->color;

Usage with custom table

if you have data stored in a custom table you can use QuentinGab\Models\Model to interact with the database. Under the hood it only use default WordPress object $wpdb.

Example of a custom table

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);

Create a Model class

class Event extends QuentinGab\Wodel\Models\Model
{
    protected $table = 'events';
    
    protected $primary_key = "id";
    
    protected $fillable = [
        'title'
    ];

    protected $casts = [
        'active' => 'bool',
    ];
}

Get Model

$all = Event::all();
$only_active = Event::where(['active'=>true]);
$with_primary_key_1 = Event::find(1);

Save Model

$new_event = new Event(['title'=>'my new event','active'=>false]);
$new_event->save();

Change log

Please see CHANGELOG for more information on what has changed recently.

Testing

$ composer test

Contributing

Please see CONTRIBUTING and CODE_OF_CONDUCT for details.

Security

If you discover any security related issues, please email quentin.gabriele@gmail.com instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.