PHP code example of anthonybudd / wp_model

1. Go to this page and download the library: Download anthonybudd/wp_model library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

anthonybudd / wp_model example snippets



Class Product extends WP_Model
{
    public $postType = 'product';
    public $attributes = [
        'color',
        'weight'
    ];
}

Product::register();

$book = new Product;
$book->title = 'WordPress for dummies';
$book->color = 'Yellow';
$book->weight = 100;
$book->save();


Class Product extends WP_Model
{
    public $postType = 'product';

    public $attributes = [
        'color',
        'weight'
    ];
    
    public $prefix = 'wp_model_'; // Optional
}

Product::register();

Product::register([
    'singular_name' => 'Product'
]);

$product = new Product();
$product->color = 'white';
$product->weight = 300;
$product->title = 'the post title';
$product->content = 'the post content';
$product->save();

$product = new Product([
    'color' => 'blue',
    'weight' => '250'
]);
$product->save();

$product = Product::insert([
    'color' => 'blue',
    'weight' => '250'
]);

$product = Product::find(15);

try {
    $product = Product::findorFail(15);
} catch (Exception $e) {
    echo "Product not found.";
}

$allProducts = Product::all();

$firstProducts = Product::in([1, 2, 3, 4]);

Product::query()
    ->meta('meta_key', 'meta_value')
    ->meta('meta_key', 'compare', 'meta_value')
    ->meta('meta_key', 'compare', 'meta_value', 'type')

Product::query()
    ->tax('taxonomy', 'terms')
    ->tax('taxonomy', 'field', 'terms')
    ->tax('taxonomy', 'field', 'operator', 'terms')

Product::query()
    ->params(['orderby' => 'meta_value', 'order' => 'ASC])

$products = Product::query()
    ->meta('color', 'blue')
    ->execute();

$products = Product::query()
    ->meta('color', 'red')
    ->meta('weight', '>', 2000, 'NUMERIC')
    ->tax('type', 'small')
    ->tax('category', ['office', 'home'])
    ->tax('quality', 'slug', 'high')
    ->tax('county', 'term_id', 'NOT IN', [1, 5])
    ->params(['orderby' => 'meta_value menu_order title'])
    ->execute();

$product = Product::find(15);
$product->delete();

$product = Product::restore(15);

$product->hardDelete();

$product = new Product;
$product->new; // Returns (bool) true

$product = Product::find(15);
$product->new; // Returns (bool) false

$product->color = 'red';
$product->dirty; // Returns (bool) true
$product->save();
$product->dirty; // Returns (bool) false

$product->title; // Returns the post's title

$product->content; // Returns the post's content

$product->the_content; // Returns the post's content via the 'the_content' filter

Product::single(); // Returns the current model if on a single page or in the loop

Product::exists(15); // Returns (bool) true or false

Product::mostRecent($limit = 1); // Returns the most recent post

Product::mostRecent(10); // Returns the most recent 10 posts [Product, Product, Product, Product]

Product::count($postStatus = 'publish'); // Efficient way to get the number of models (Don't use count(WP_Model::all()))

$product->postDate($format = 'd-m-Y'); // Returns the post date based on the format supplied

$product->get($attribute, $default) // Get attribute from the model

$product->set($attribute, $value) // Set attribute of the model

$product->post() // Returns the WP_Post object (This will be the post at load, any updates to the post (title, content, etc) will not be reflected)

$product->permalink() // Returns the post permalink

$product->hasFeaturedImage() // Returns TRUE if a featured image has been set or FALSE if not

$product->featuredImage($defaultURL) // Returns the featured image URL

$product->toArray() // Returns an array representation of the model

Product::asList() // Returns array of posts keyed by the post's ID
[
    15 => Product,
    16 => Product,
    17 => Product
]

// You can also specify the value of each element in the array to be meta from the model.
Product::asList('post_title')
[
    15 => "Product 1",
    16 => "Product 2",
    17 => "Product 3"
]


Class Product extends WP_Model
{
    ...

    public $virtual = [
        'humanWeight'
    ];

    public function _getHumanWeight()
    {  
        return $this->weight . 'Kg';
    }
}

$product = Product::find(15);
echo $product->humanWeight;


Class Product extends WP_Model
{
    ...

    public $default = [
        'color' => 'black'
    ];
}

$product = new Product;
echo $product->color; // black


Class Product extends WP_Model
{
    ...

    public $filter = [
        'weight'
        'stock' => 'number_format',
        'seller' => Seller::class,
        'related' => Product::class,
    ];

    public function _filterWeight($value){
        return intval($value);
    }
}

$product = Product::insert([
    'weight' => 250,
    'stock' => '3450',
    'seller' => Seller::find(3),
    'related' => [
        new Product,
        new Product,
        new Product,
    ]
]);

$product->weight;  // (int) 250
$product->stock;   // (string) 3,450
$product->seller;  // (object) Seller
$product->related; // (array) [Product, Product, Product]


Class Product extends WP_Model
{
    ...

    public $serialize = [
        'humanWeight',
    ];

    public $protected = [
        'weight',
    ];

    public function _getHumanWeight()
    {  
        return $this->weight . 'Kg';
    }
}

$product = Product::find(15);
echo json_encode($product);

$greenProducts = Product::where('color', 'green');

$otherProducts = Product::where([
    [
        'key' => 'color',
        'value' => 'green',
        'compare' => '!='
    ],[
        'taxonomy' => 'category',
        'terms' => ['home', 'garden']
    ]
]);


Class Product extends WP_Model
{
    ...

    public function _finderHeavy($args)
    {  
        return [
            'meta_query' => [
                [
                    'key' => 'weight',
                    'compare' => '>',
                    'type' => 'NUMERIC',
                    'value' => '1000'
                ]
            ]
        ];
    }

    // Optional
    public function _postFinderHeavy($results)
    {  
        return array_map(function($model){
            if($model->color == 'green'){
                return $model->color;
            }
        }, $results);
    }


    // Finder with optional args
    public function _finderHeavyWithArgs($args)
    {  
        return [
            'paged'      => $args['page'], // 3
            'meta_query' => [
                [
                    'key' => 'weight',
                    'compare' => '>',
                    'type' => 'NUMERIC',
                    'value' => '1000'
                ]
            ]
        ];
    }
}

$heavyProducts = Product::finder('heavy');

// Finder with optional args
$heavyProducts = Product::finder('heavyWithArgs', ['page' => 3]); 

Class Product extends WP_Model
{
    ...
    
    public function saving(){
        echo "The save method has been called, but nothing has been written to the database yet.";
    }
    
    public function saved($model){
        echo "The save method has completed and the post and it's meta data have been updated in the database.";
        echo "The Model's ID is". $model->ID;
    }
}

Class Product extends WP_Model
{
    ...
    public $taxonomies = [
        'category',
    ];
}

$product = Product::insert([
    'title' => 'product',
    'color' => 'blue',
    'weight' => '250',
    'category' => ['home', 3]
]);

$product->category; // ['Home', 'Office'];

$product->getTaxonomy('category'); // [WP_Term, WP_Term];
$product->getTaxonomy('category', 'term_id'); // [2, 3];
$product->getTaxonomy('category', 'name'); // ['Home', 'Office'];

$product->addTaxonomy('category', 'home');
$product->addTaxonomy('category', 3);

$product->addTaxonomies('category', ['home', 'office']);
$product->addTaxonomies('category', ['home', 3]);
$product->addTaxonomies('category', [2, 3]);

$product->removeTaxonomy('category', 'home');
$product->removeTaxonomy('category', 3);

$product->removeTaxonomies('category', ['home', 'office']);
$product->removeTaxonomies('category', [2, 3]);

$product->clearTaxonomy('category');
$product->getTaxonomy('category'); // [];