Creating the property types taxonomy

WordPress taxonomies are a way of grouping posts or custom post types. We already looked at taxonomies while discussing database tables and templates in previous chapters. In this section, we are going to look at how taxonomies fit into custom post types and their implementation. In this scenario, we are building a property listing site. We can use taxonomies to group properties based on the property type. Let's begin by adding the following action to the constructor of the WQCPT_Model_Property class:

$this->property_category_taxonomy  = 'wqcpt_property_listing_type';
add_action( 'init', array( $this, 'create_property_custom_taxonomies' ) );

As with custom post types, we have to use the init action to register taxonomies for WordPress. Let's consider the implementation of the create_property_custom_taxonomies function:

public function create_property_custom_taxonomies() {
$category_taxonomy = $this->property_category_taxonomy;
$singular_name = __('Property Listing Type','wqcpt');
$plural_name = __('Property Listing Types','wqcpt');

register_taxonomy(
$category_taxonomy,
$this->post_type,
array(
'labels' => array(
'name' => sprintf( __( '%s ', 'wqcpt' ) , $singular_name),
'singular_name' => sprintf( __( '%s ', 'wqcpt' ) , $singular_name),
'search_items' => sprintf( __( 'Search %s ', 'wqcpt' ) , $singular_name),
),
'hierarchical' => true,
)
);
}

We start the function by defining the taxonomy and the necessary labels, similar to the custom post types. Then, we can call the register_taxonomy function with the necessary parameters to create the taxonomy for property types. Let's take a look at the parameters in detail:

The choice of category against tag for taxonomies depends on your requirements. Generally, we use categories when we want to have different sub-levels as well as when have a fixed set of primary options. Tags don't provide sub-levels and usually use a dynamic set of values to explain the data. In this scenario, property listing types have predefined options such as Sale, Rent, and Mortgage. Therefore, we choose category over tags for property listing types.

Once this code is used, you will see a new taxonomy added to the Property menu. You can create properties and assign property listing types to categorize the properties based on your needs. In real-world requirements, you have to match the taxonomy needs of each custom post type with categories or tags depending on the functionality.