Skip to content

Instantly share code, notes, and snippets.

@orangerdev
Last active January 4, 2018 04:57
Show Gist options
  • Save orangerdev/25bd747d5504288be9ac45e0a5cfd7a1 to your computer and use it in GitHub Desktop.
Save orangerdev/25bd747d5504288be9ac45e0a5cfd7a1 to your computer and use it in GitHub Desktop.
Wordpress Chained Class to register post type
<?php
namespace sejoli;
Class PostType
{
protected static $labels = [];
protected static $args = [];
protected static $post_type = '';
protected static $valid = true;
protected static $exists = true;
protected static $respond = [];
/**
* Set post type label
* @param array $label
*/
static public function set_labels(array $labels)
{
self::$labels = $labels;
return new static;
}
/**
* Set post type arguments
* @param array $args
*/
static public function set_args(array $args)
{
$defaults = [
'label' => '',
'description' => '',
'labels' => self::$labels,
'supports' => ['title', 'editor'],
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => true,
'publicly_queryable' => true,
'capability_type' => 'post',
];
self::$args = wp_parse_args($args,$defaults);
return new static;
}
/**
* Set post type key
* @param string $post_type
*/
static public function set_post_type($post_type)
{
if(!$post_type || empty($post_type)) :
self::$valid = false;
self::$respond['message'][] = __('Post type is not set','sejoli');
elseif(!is_string($post_type)) :
self::$valid = false;
self::$respond['message'][] = __('Post type is not string type','sejoli');
else :
self::$post_type = $post_type;
endif;
return new static;
}
/**
* Validating post type arguments
*/
static protected function validate()
{
// make sure again
// check if user bypass the process set
if(true === self::$valid) :
self::set_post_type(self::$post_type);
endif;
}
/**
* Check if current post type exists
*/
static protected function exists()
{
if(!post_type_exists(self::$post_type)) :
self::$exists = false;
endif;
}
/**
* Flush rewrite rules
*/
static protected function flush()
{
if(false === self::$exists) :
flush_rewrite_rules(true);
endif;
}
/**
* Register the post type
*/
static public function register()
{
self::validate();
if(true === self::$valid) :
self::$args['labels'] = self::$labels;
register_post_type(self::$post_type,self::$args);
self::flush();
self::$respond['message'][] = sprintf(__('Post type %s registered','sejoli'),self::$post_type);
endif;
return new static;
}
/**
* Return the respond
* @return array
*/
static public function respond()
{
self::$respond['valid'] = self::$valid;
return self::$respond;
}
}
@orangerdev
Copy link
Author

Example

$respond = \sejoli\PostType::set_labels($labels)
->set_args($args)
->set_post_type('affiliate')
->register()
->respond();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment