Dave Jesch- WordCamp San Diego 2015- Object Oriented Programming and WordPress
Scalability and stability is a MUST in today's plugin development world. A solid architecture promotes healthy expandable code. Objected Oriented Programming can take your code into new realms of possibilities.
new instance of a class $cake = new ChocolateCake(); $cake->add_ingredients('flour', 'spices') $cake->add_ingredients('milk', 'egg'); $cake->bake(); $cake->add_frosting(); $cake->eat();
function __construct() { add_action('init', array(&$this, 'init')); if (is_admin()) add_action('admin_init', array(&$this, 'admin_init')); else add_action('wp_enqueue_scripts', array(&$this, 'enqueue_scripts')); add_filter('the_content', array(&$this, 'content_filter'), 10, 1); register_activation_hook(__FILE__, array(&$this, 'activation_hook'); } public function init() { ... } public function admin_init() { ... } public function enqueue_scripts() { ... } public function content_filter($content) { ...; return ($content); } public function activation_hook() { ... } } new MyPlugin(); Sample Object Oriented Plugin
class OOMetaBoxPlugin { private function __construct() { add_action('init', array(&$this, 'init')); } // Create the metabox, setting the CSS class, title, etc. public function init() { // create the metabox instance new DemoMetaBox(); } } new OOMetaBoxPluin();
class DemoMetaBox extends SpectrOMMetaBox { // Create the metabox, setting the CSS class, title, etc. public function __construct() { parent::__construct( 'oo-image-meta', // CSS class for metabox __('Set Image', 'oometaboxdemo'), // metabox title array(&$this, 'output_metabox') // metabox callback // remaining parameters are defaults ); } // output metabox contents public function output_metabox($post) { ... } }
class SpectrOMQueryTestimonials extends SpectrOMQueryModel { public function __construct() { parent::__construct('testimonials'); // optionally customize this model $this->set_posts_per_page(5) ->no_found_rows(); } }
Model $testimonials = new SpectrOMQueryTestimonials(); $testimonials->set_posts_per_page(3) // optionally change # per page ->add_pagination() // optionally add paged for archive // ->set_page(2) ->order_by('title', 'ASC'); $query = $testimonials->get_query(); // now do a standard "Loop" while ($query->have_posts()) { $query->the_post(); // continue as normal }
$settings = new SpectrOMSettings($args); add_options_page('My Settings', 'My Settings', // page title / menu title 'manage_options', // capability $settings->get_page(), // menu slug 'settings_page_callback')); // callback function function settings_page_callback() { global $settings; echo '<div class="wrap">'; echo '<h2>', $settings->get_header(), '</h2>'; echo '<form action="options.php" method="post">'; // use the settings object to output sections and fields $settings->settings_fields(); $settings->settings_sections(); submit_button(); echo '</form>'; echo '</div>'; }