-
Notifications
You must be signed in to change notification settings - Fork 3
Model
Damien Couteillou edited this page Mar 26, 2018
·
2 revisions
A model is the representation of a custom post type (CPT) in WP.
Models are found into the app/Models folder.
To make your CPT available to WP you need to initialize it into the functions.php
file.
new \Ayctor\Models\Example;
wp blueprint model --name=Example
<?php
namespace Ayctor\Models;
use WpCore\Models\Model;
class Example extends Model
{
/**
* Internal name for the CPT
* @var string
*/
protected $post_type = 'example';
/**
* Auto-generating labels for cpt
* @var string
*/
protected $label = 'Example';
/**
* CPT args from register post type function
* https://developer.wordpress.org/reference/functions/register_post_type/
* @type array
*/
protected $cpt_args = [
'public' => true,
'publicly_queryable' => true,
'exclude_from_search' => false,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'query_var' => true,
'capability_type' => 'post',
'has_archive' => false,
'hierarchical' => false,
'menu_icon' => 'dashicons-carrot',
'rewrite' => true,
'menu_position' => null,
'supports' => ['title'],
];
/**
* Taxonomies args from register taxonomy function
* https://developer.wordpress.org/reference/functions/register_taxonomy/
* @type array
*/
protected $taxonomies = [
'carrot_cat' => [
'label' => 'Country',
'hierarchical' => true,
'rewrite' => ['slug' => '/country']
],
'carrot_tag' => [
'label' => 'Colors',
'hierarchical' => false,
'rewrite' => ['slug' => '/colors']
],
];
/**
* Register fields for CPT/Taxonomies
* Full documentation for fields :
* https://www.advancedcustomfields.com/resources/register-fields-via-php/
* Custom columns and custom filters in admin
*/
protected function register()
{
// CPT fields
$this->groupCpt('example_meta', 'Test');
$this->field('example_meta', [
'type' => 'text',
'name' => 'test',
'label' => 'Test',
]);
// Taxonomy fields
$this->groupTax('country_meta', 'Test', 'carrot_cat');
$this->field('country_meta', [
'type' => 'text',
'name' => 'test',
'label' => 'Test',
]);
// Columns
$this->column('cb', '<input type="checkbox" />', true);
$this->column('title', 'Title', true);
$this->column('test', 'Test', false, 'meta');
$this->column('carrot_cat', 'Country', false, 'term');
$this->column('carrot_tag', 'Colors', false, 'term');
$this->column('carrot_custom', 'Custom', false, 'custom', 'My custom value');
$this->column('date', 'Date', true);
// Filters
$options = ['' => 'Carrot radio test', 'yes' => 'Yes', 'no' => 'No'];
$this->filter('carrot_radio', $options);
}
}
public function __construct()
{
parent::__construct();
add_action('acf/save_post', [$this, 'savePost']);
}
public function savePost($post_id)
{
if ($this->post_type == $_POST['post_type']) {
if (!current_user_can('edit_post', $post_id)) {
return;
}
} else {
return;
}
// Your action
}