WordPress Model class methods - markhowellsmead/helpers GitHub Wiki
Basic class
<?php
namespace MHM\Theme\Model;
class CustomsForm
{
const POST_TYPE = 'my_posttype';
const POST_TYPE_PLURAL = 'my_posttypes';
}
Create a new Post
public function create(array $args)
{
if (!current_user_can('edit_' .POST_TYPE_PLURAL)) {
return null;
}
$defaults = [
'post_author' => get_current_user_id(),
'post_title' => 'Untitled',
'post_status' => 'draft',
'meta' => []
];
$args = wp_parse_args($args, $defaults);
// Force the post type, so that it's overridden if passed as an argument
$args['post_type'] = self::POST_TYPE;
$meta = $args['meta'];
unset($args['meta']);
$post_id = wp_insert_post($args);
if ($post_id) {
foreach ($meta as $key => $value) {
update_post_meta($post_id, $key, $value);
}
}
return $post_id;
}