Skip to content
This repository has been archived by the owner on May 31, 2021. It is now read-only.

Block API

sy4mil edited this page Oct 16, 2012 · 6 revisions

If you're familiar with the Widgets API, then adding a custom block should be a walk in the park.

Adding a custom block consists of two steps:

  1. Extends the AQ_Block class
  2. Register the block using aq_register_block($classname)

1. Extending the AQ_Block class

The basic structure:

class My_Custom_Block extends AQ_Block {

	function __construct() {
		// block actual processes
	}

 	function form( $instance ) {
		// outputs the options form on admin
	}

	function update( $new_instance, $old_instance ) {
		// processes block options to be saved
	}

	function block( $instance ) {
		// outputs the content of the block
	}

}

2. Registering the block

aq_register_block('AQ_Text_Block');

Example:

It would be much easier to explain this with a code example. Below is how I added the default text block:

/** A simple text block **/
class AQ_Text_Block extends AQ_Block {
	
	//set and create block
	function __construct() {
		$block_options = array(
			'name' => 'Text',
			'size' => 'span6',
		);
		
		//create the block
		parent::__construct('aq_text_block', $block_options);
	}
	
	function form($instance) {
		
		$defaults = array(
			'text' => '',
		);
		$instance = wp_parse_args($instance, $defaults);
		extract($instance);
		
		?>
		<p class="description">
			<label for="<?php echo $this->get_field_id('title') ?>">
				Title (optional)
				<input id="<?php echo $this->get_field_id('title') ?>" class="input-full" type="text" value="<?php echo $title ?>" name="<?php echo $this->get_field_name('title') ?>">
			</label>
		</p>
		
		<p class="description">
			<label for="<?php echo $this->get_field_id('text') ?>">
				Content
				<textarea id="<?php echo $this->get_field_id('text') ?>" class="textarea-full" name="<?php echo $this->get_field_name('text') ?>" rows="5"><?php echo $text ?></textarea>
			</label>
		</p>
		<?php
	}
	
	function block($instance) {
		extract($instance);
		echo do_shortcode(htmlspecialchars_decode($text));
	}
	
}
aq_register_block('AQ_Text_Block');

Additional Notes

  • The parent::_construct() function is required in the __construct() function of your custom block. The $block_options array is optional.

  • For the form, use the get_field_id('option_id') and get_field_name('option_id') for the id & name HTML attributes respectively.

  • If you want to make sure that the block is child-theme proof, make sure to wrap the sub-class in if(!class_exists('My_Custom_Block')) {}