taxonomies in wordpress

Taxonomies in WordPress. What are they for? How are they created?

Have we ever wondered how we can create new classifications (taxonomies) in WordPress. For example, you could have a movie site and there is a term that classifies them by genre (Drama, Terror or Adventures). I could have a portfolio to show my works and want to filter them by a classification that identifies them as: Type of Portfolio (Responsive Web, E-commerce or Web Business), for this purpose there are taxonomies and in this post we will detail them.

What is a taxonomy?

The word taxonomy comes from Greece and is used for the process of classification or ordering of objects, meanings, types of knowledge, etc. In Greek taxo means ordering and organizations; So it is easy to deduce that it is a taxonomy, but if you do not understand it yet, just think of it as something to group together certain elements that have something in common.

What is a taxonomy in WordPress?

After getting an idea of ​​what taxonomy means, taking it to the WordPress context is easy. WordPress you use them to sort and group post_type, either those that come by defects such as page and post, or those that we define through the Custom Post Type (CPT), by the way if you don’t know what a Custom Post Type is, read this article about them:

Hierarchical and non-hierarchical taxonomies

There are two types of taxonomies in WordPress: hierarchical and non-hierarchical. The hierarchical ones are like the categories that we find in a basic WordPress installation, they support a parent-child structure, which is nothing more than a category can have sub-categories, for example the Animal category can have sub-categories like: Mammals , Birds and Reptiles, even Birds can have sub-categories such as: Turkeys, Chickens or Canaries and so on forming a tree structure. Non-hierarchical ones are simpler and more linear like WordPress tags and are mostly used to classify objects without having to depend on a parent element, for example the colors Blue, Green or Yellow.

How to create a taxonomy in WordPress?

To create a taxonomy in WordPress is simple, it’s just two steps.

1 – Create a function that will define the taxonomy.

add_action('init', 'wr_portfolio_taxonomies');

This function has two variables inside $labels, $args and a register_taxonomy() function. The $labels variable is an array that has all the taxonomy customization tags.

$args :It has a set of properties such as: hierarchical that defines whether the taxonomy will be hierarchical or not; labels property receiving the $labels tag array; show_admin_colum defines if a column will be shown in the table of the post_type that make up the taxonomy; rewrite defines the post_type that will be classified by the taxonomy.

2- Call the hook that creates the taxonomy.

function wr_portfolio_taxonomies(){
    
    $labels = array(
        'name' => 'Types Portfolio',
        'singular_name' => 'Type Portfolio',
        'search_items' => 'Search Types Portfolio',
        'all_items' => 'All Types Portfolio',
        'parent_item' => 'Parent Type Portfolio',
        'parent_item_colon' => 'Parent Type Portfolio:',
        'edit_item' => 'Edit Type Portfolio',
        'update_item' => 'Update Type Portfolio',
        'add_new_item' => 'Add New Type Portfolio',
        'new_item_name' => 'New Type Portfolio Name',
        'menu_name' => 'Types Portfolio'
    );

    $args = array(
        'hierarchical' => true,
        'labels' => $labels,
        'show_ui' => true,
        'show_admin_column' => true,
        'query_var' => true,
        'rewrite' => array('slug' => 'type_portfolio')
    );

    register_taxonomy( 'type_portfolio', array('portfolio'), $args );
}

You just need to call the init action to complete the registration process of the new taxonomy.

Conclusion

As we have seen taxonomies play a fundamental role in WordPress, its use greatly enhances this technology. Taxonomies make this CMS (Content Management System) not only a blog, but what your mind can create. We can create hotel reservation sites, websites that create events and even as a strong competition to develop virtual stores. Check more about taxonomies in WordPress Official Doc.

If you want to keep learning about WordPress development, read this articles:

Hooks in WordPress

Custom Post Type in WordPress (CPT)

How to create a plugin in WordPress?

 

Add extra fields to categories without plugin

Add extra fields to categories without plugin (WordPress)

Many times we need to add extra fields to the categories in WordPress, mainly to customize the category.php template or to handle new data related to the category such as images, styles and even html content.

The default wordpress categories come like this, with only four fields (name, slug, parent category and description).

Default WordPress category page

How to add other custom fields in WordPress?

Here is how we have added three more fields to the categories. How?

HOW TO ADD OTHER CUSTOM FIELDS IN WORDPRESS?

Step # 1

First we must add the edit_category_form_fields hook that allows us to modify the category view to add new html elements such as textfield, buttons, texarea and others.

<?php

//add extra fields to category edit form hook
add_action ( 'edit_category_form_fields', 'extra_category_fields');
//add extra fields to category edit form callback function
function extra_category_fields( $tag ) {    //check for existing featured ID
    $t_id = $tag->term_id;
    $cat_meta = get_option( "category_$t_id");
?>
<tr class="form-field">
<th scope="row" valign="top"><label for="cat_Image_url"><?php _e('Category Image Url'); ?></label></th>
<td>
<input type="text" name="Cat_meta[img]" id="Cat_meta[img]" size="3" style="width:60%;" value="<?php echo $cat_meta['img'] ? $cat_meta['img'] : ''; ?>"><br />
            <span class="description"><?php _e('Image for category: use full url with '); ?></span>
        </td>
</tr>
<?php
}

Step # 2

In this step, basically what we do is save the information in the wordpress database, specifically in the wp_options table, the hook edited_category is used for this.

<?php
// save extra category extra fields hook
    add_action ( 'edited_category', 'save_extra_category_fileds');

// save extra category extra fields callback function
    function save_extra_category_fileds( $term_id ) {
        if ( isset( $_POST['Cat_meta'] ) ) {
            $t_id = $term_id;
            $cat_meta = get_option( "category_$t_id");
            $cat_keys = array_keys($_POST['Cat_meta']);
                foreach ($cat_keys as $key){
                if (isset($_POST['Cat_meta'][$key])){
                    $cat_meta[$key] = $_POST['Cat_meta'][$key];
                }
            }
            //save the option array
            update_option( "category_$t_id", $cat_meta );
        }
    }

Step # 3

The last step is to use the values, as I said at the beginning, mostly these values are used to extend the view of the category template category.php, such as defining a main image for each category.

<?php
if (isset($cat_data['img'])){
    $cat_img=$cat_data['img'];
}
?>

<section id="jumbotron">
        <div class="container jumbotron jumbotron-fluid mb-0" style="background: <?php echo $cat_bg_color ?>; max-width: 100%;background-size: cover;color:<?php echo $cat_font_color ?> !important">
        
          <div class="container">
            <div class="row">
                <div class="col-md-6">
                    <img src="<?php echo $cat_img ?>" class="img-fluid" alt="Category Image">
                </div>
            </div>
          </div>


Conclusion

There are several plugins in wordpress to add extra fields to the categories, but this could pose some problems such as: performance, illegibility of the code and even full and unreadable  wordpress interface with more menu and visual elements. If you are creating a theme from the beginning, you will want to depend as little as possible that your theme requires other plugins for proper operation, which is why adding the fields in this way makes our site simpler.