WordPress Software Development at H1. Part 3: Application Code

PostType classes

Since WordPress is a CMS, the most important thing is content. So let’s first look into what would a post type class look like.

namespace ProjectName\PostType;

/**
 * Page, a WordPress default post type
 */
class Page extends \WPlinth\PostType {

	const TYPE = 'page';

	public function set_registration_parameters() {
	}

	public function set_meta_boxes() {
	}

}

Both WordPress default post types, Page and Post, can be defined as a class that extends the WPlinth PostType class. This is not necessary, if your application does nothing to extend the functionality of those types. However, from the simplistic example above, we can see how a PostType class is constructed. We define the post type name as a class level constant. Then we have two functions, set_registration_parameters and set_meta_boxes that will be called automatically, if they are defined, by the base class. Below, you can see a more realistic example:

namespace ProjectName\PostType;

/**
 * Service post type
 * Represents a service provided to a customer,
 * e. g. Project Management or Maintenance.
 */
class Service extends \WPlinth\PostType {

	const TYPE = 'projectname_service';

	public function set_registration_parameters() {
		$this->labels = array( 
			'menu_name'          => __( 'Services', 'projectname-application' ),
			'name'               => _x( 'Services', 'post type general name', 'projectname-application' ),
			'singular_name'      => _x( 'Service', 'post type singular name', 'projectname-application' ),
			'name_admin_bar'     => _x( 'Service', 'add new on admin bar', 'projectname-application' ),
			'add_new'            => _x( 'Add New', 'service', 'projectname-application' ),
			'add_new_item'       => __( 'Add New Service', 'projectname-application' ),
			'new_item'           => __( 'New Service', 'projectname-application' ),
			'edit_item'          => __( 'Edit Service', 'projectname-application' ),
			'view_item'          => __( 'View Service', 'projectname-application' ),
			'all_items'          => __( 'All Services', 'projectname-application' ),
			'search_items'       => __( 'Search Services', 'projectname-application' ),
			'parent_item_colon'  => __( 'Parent Services:', 'projectname-application' ),
			'not_found'          => __( 'No services found.', 'projectname-application' ),
			'not_found_in_trash' => __( 'No services found in Trash.', 'projectname-application' ),
		);

		/**
		 * Define other arguments
		 */
		$this->args = array(
			'rewrite'  => array( 'slug' => 'services' ),
			'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'revisions' ),
		);
	}

	public function set_meta_boxes() {
		$this->meta_boxes[] = array(
			'title' => 'Pricing',
			'pages' => array( self::TYPE ), // Array of post types
			'context'    => 'normal',
			'priority'   => 'high',
			'fields' => array(
				array(
					'id'   => 'projectname_service_hourly_price',
					'name' => __( 'Hourly price', 'projectname-application' ),
					'type' => 'text',
				),
				array(
					'id'   => 'projectname_service_daily_price',
					'name' => __( 'Daily price', 'projectname-application' ),
					'type' => 'text',
				),
			),
		);
	}

}

In set_registration_parameters we do two things. First we set the labels to an instance variable labels. Then we do that for other arguments of register_post_type. The base class takes care of the rest.

In set_meta_boxes we append to the meta_boxes array the meta fields we would like our post type have. We use the format shared with plugins Custom Meta Boxes and Meta Box. One of those plugins should be active. If you would like to use something else, you can extend ProjectName\PostType and take care of that part yourself.

Taxonomy classes

Taxonomies work a lot the same way than post types. Below is a sample. It should be pretty self-explanatory.

namespace ProjectName\Taxonomy;

class CaseType extends \WPlinth\Taxonomy {
	const TAXONOMY = 'projectname_casetype';

	public function set_taxonomy_data() {

		$labels = array(
			'name'					=> _x( 'Case Type', 'Taxonomy plural name', 'projectname-application' ),
			'singular_name'			=> _x( 'Case Type', 'Taxonomy singular name', 'projectname-application' ),
			'search_items'			=> __( 'Search Case Types', 'projectname-application' ),
			'popular_items'			=> __( 'Popular Case Types', 'projectname-application' ),
			'all_items'				=> __( 'All Case Types', 'projectname-application' ),
			'parent_item'			=> __( 'Parent Case Type', 'projectname-application' ),
			'parent_item_colon'		=> __( 'Parent Case Type', 'projectname-application' ),
			'edit_item'				=> __( 'Edit Case Type', 'projectname-application' ),
			'update_item'			=> __( 'Update Case Type', 'projectname-application' ),
			'add_new_item'			=> __( 'Add New Case Type', 'projectname-application' ),
			'new_item_name'			=> __( 'New Case Type', 'projectname-application' ),
			'add_or_remove_items'	=> __( 'Add or remove Case Type', 'projectname-application' ),
			'choose_from_most_used'	=> __( 'Choose from most used Case Types', 'projectname-application' ),
			'menu_name'				=> __( 'Case Type', 'projectname-application' ),
		);
	
		$args = array(
			'labels'            => $labels,
			'public'            => true,
			'show_in_nav_menus' => true,
			'show_admin_column' => true,
			'hierarchical'      => true,
			'show_tagcloud'     => true,
			'show_ui'           => true,
			'query_var'         => true,
			'rewrite'           => array( 'slug' => 'case-type' ),
			'query_var'         => true,
		);

		$this->args = $args;

		$this->types = array( 'projectname_casestudy' );
	}

}

Connection classes

If we want to define a Posts to Posts connection, we extend the \WPlinth\Connection class. Here is a simple example:

namespace ProjectName\Connection;

class ServicesProvided extends \WPlinth\Connection {

	const NAME = 'services_provided';

	protected $connection_type;

	public function set_connection_type() {
		$this->connection_type = array(
			'name'  => self::NAME,
			'from'  => 'projectname_casestudy',
			'to'    => 'projectname_service',
			'cardinality' => 'one-to-many',
			'title' => array(
				'from' => __( 'Casestudies', 'projectname-application' ),
				'to' => __( 'The Service', 'projectname-application' )
			),
		);
	}
}

All the functionality that is related to the connection should be put into this class. We might, for example, want a function to fetch all the services provided for a case. That would look like something like this:

public function get_services( $casestudy_id ) {
		$services = p2p_get_connections(
			self::NAME,
			array( 'from' => $casestudy_id, 'to' => 'any' )
		);
		return $services;
}

Even this simple function does make sense to exist, since this way we are able to encapsulate all the logic that is touching Posts 2 Posts API and thus keep all other code not dependant on that particular implementation. The code that would need to consume this function would need to have an instance of our ServicesProvided class. And, you guessed it, that instance would be provided to your consuming class by the DependencyInjection container, provided that you had defined the dependency in the configuration file.

QueryFilter classes

We are using QueryFilters to modify the main query for specific views. Instead of having a mess of unreadable if else statements, we define separate classes for each modification. Let’s look at an example. Say we wanted to display case studies in addition to posts on the front page.

namespace ProjectName\QueryFilter;

/**
 * Display posts and case studies on front page
 */
class FrontPage extends \WPlinth\QueryFilter {
	const PRIORITY = 10;

	public function test( $query ) {
		return $query->is_home();
	}

	public function filter( $query ) {
		$query->set( 'post_type', array(
			ProjectName\PostType\Post::TYPE,
			ProjectName\PostType\CaseStudy::TYPE
		);
	}
}

A QueryFilter consists of three parts. First, we can define a priority. Filters are tested in the order of their priority and only one filter is run per page load. Lower number means earlier execution.

QueryFilters in the system are tested first. The test function should return true, if the query does match the view WordPress is executing. In our example, we are simply testing weather WordPress thinks the current page is home page.

If the test matches, filter function is run. There we have the opportunity to do the modifications to the query we like.

Going further

These are just the most common ways of modifying and extending WordPress for a project specific way. If your application does something else, say, defines multiple shortcodes, it would make sense to create a base class for those and group them in a namespace/folder, in a similar fashion than what I have demonstrated above.

Other than that, this is it, a better way to organize your application code.

In the next part, we are going to discuss writing unit test.