Hooks in Wordpress

Hooks in WordPress

Hooks in WordPress are a very useful tools, WP is known to base its operation on events and procedures. During the system run cycle there are different parts that run at different times. In the ecosystem of this framework, hooks are one of the most powerful tools. It is notable that thanks to them the operation of the site can be modified at different points, through code. In this way, understanding how they work is one of the most important goals to be achieved as a developer. Hooks form the basis of plugin and theme activity because they facilitate adding their functionalities to the system. At the same time, they are the channels of interaction of the custom code with the WordPress core. Even the same core uses them extensively. In this article hooks will be characterized, their structure and way of operation will be explained, their classification will be described and examples of how to use them will be shown.

How are hooks classified?

In general there are 2 types of hooks: action hooks and filter hooks. To use either one, the same structure is declared. When using any type of hook, you need a function in which the desired code will be executed, and then a call to a method that registers this function, called callback, on behalf of a specific hook. Action hooks interrupt the natural flow of the WordPress code to run the code added by the developer. After this, they return to the natural execution of the system without modifying anything. In short: they interrupt the flow of site code, execute custom code, and follow the normal flow of system execution. Action hooks do not return a value. For their part, filter hooks change the information they receive, in a specific way. That modified information will then be used by another part of the code. Filter hooks are always expected to return some element.

Estructura de los action hooks y grupos en los que se dividen

The structure of an action hook is as follows:

// Action Hook Structure
add_action(string $action, callable $function_identifier, int $priority, int $quantity_parameters);

in which the following parameters exist:

  • $action: required parameter of type text string. It is the identifier of the action (hook, hook) to which the function that is passed by $ identifier_my_function will hook.
  • $function_identifier: required parameter of text string type. It is the identifier of the function that is created to execute custom code, the operation to be performed.
  • $priority: optional parameter of type integer. Declare the order in which each method related to this hook will be executed. If this parameter is omitted, it has a default value of 10. The lower the number, the higher your priority. If there is an equal value for more than one function hooked to the same hook, the conflict is resolved by ordering the functions according to the moment in which the procedure of hooking the function to the hook was performed.
  • $quantity_parameters: optional parameter of type integer. Defines the number of parameters that are passed to the function. If not declared, by default the value 1 is taken.

There are many action hooks. The official WordPress documentation catalogs them in 10 groups, according to different criteria:

Action hooks categories Descriptionn
Action hooks that are executed during a typical request They are executed when a logged in user opens the main page of the site
Action hooks that are executed during the request for an administrative page Called when a logged in user opens the posts page
Action hooks related to pages, posts, attachments or categories from the administration Executed when adding, removing, editing, or updating operations are performed on a page, post, attachment, or category. Also included are action hooks that are executed when doing these operations with taxonomies
Action hooks related to trackback, pings and comments They are executed when certain operations are performed on these elements of the WordPress logic
Action hooks from blogroll Run when blogroll links are added, removed, or edited
Action hooks related to the feed They run at the time the site feed operations are performed
Action hooks related to the topic Are called when operations related to the site theme are completed
Action hooks related to administrative activities They are executed at the time of performing an operation that can only be completed from administrative profiles
Action hooks advanced They run when WordPress is determining which posts to show, when the loop runs, when plugins are activated, and others of that nature
Action hooks related to administrative logging They are executed when the login page performs operations for management, authentication, password reset and others of the user management type.

Structure of the filter hooks and groups into which they are divided

Filter hooks have the following structure:

// Estructura filter hook
add_filter(string $filtro, callable $identificador_mi_funcion, int $prioridad, $cantidad_parametros);

 

only the first parameter differs from action hooks:

  • $filter: required parameter of type text string. It is the identifier of the filter hook to which the function that is passed by $identifier_my_function will hook.

There are also many filter hooks. The official WordPress documentation determines 19 groups, according to different criteria:

Categories of filter hooks Description
Filter hooks related to database operations on posts, pages and attachments They are executed when reading and writing operations are performed in the database on this type of WordPress elements
Filter hooks related to database operations on pings, comments and trackbacks They run when executing read and write operations in the database on this type of elements
Filter hooks related to link database operations Refers to filters related to links to pages, posts, files, feeds and others. Does not refer to blogroll links
Filter hooks related to dates and times Process information about date and time generated by WordPress functions
Filter hooks related to authors and users They process information that is read and written to the database that deals with authors and users of the system
Filter hooks related to blogroll Contains filters related to blogroll links
Filter hooks related to blog information and options Groups filters that process information obtained and saved in the database about the blog and its options
Filter hooks related to general text Contains filters that process text in a general way
Filter administrative hooks Filters in this category relate to WordPress administrative pages
Filter hooks for the rich text editor These filters modify the settings of the rich text editor
Filter hooks related to the topic This category contains filters that process links, themes, templates, and theme style files
Filter hooks related to user registration and login Contains filters to process authentication, user registration errors and emails, validation of user names, and attempted authentication of an already authenticated user
Filter hooks related to redirect and rewrite These filters have to do with WordPress handling of rewriting rules
WP_Query filter hooks These filters are executed by the WP_Query object while building and executing queries to the database
Filter hooks related to media files Groups filters that are used to integrate images, photos and audios
Advanced filter hooks Includes advanced filters related to internationalization, miscellaneous queries and other fundamental WordPress functions
Filter hooks related to widgets Contains filters added by widgets present in the WordPress core
Filter hooks related to the administrative bar These filters are related to the administrative bar added in WordPress version 3.1.0

How to use an action hook

An example of how to use an action hook in WordPress would be the following:

// Archivo: /wp-content/themes/mi-tema/functions.php

/**
 * Action hook
 */
function my_action_hook_code(){
    echo '<h1>Custom code inserted from a hook</h1><br>';
}

// Hook
add_action('init', 'my_action_hook_code');

In this case, the hooking of the ‘my_action_hook_code’ function is performed on the ‘init’ action, without determining priority, which defaults to 10 when executing the function. The ‘init‘ action is typically used by plugins to initialize. It belongs to the group of actions that are executed during home page requests.

How to use a filter hook

An example of how to use a filter hook in WordPress would be the following code snippet:

// Archivo: /wp-content/themes/mi-tema/functions.php

/**
 * Filter hook
 */
function my_filter_hook_code($excerpt_text){
    $excerpt_text = '<i>Código personalizado anclado al filter hook \'the_excerpt\'</i><br><br>';
    return $excerpt_text;
}

// Hook
add_filter('the_excerpt', 'my_filter_hook_code');

In the example, the function ‘my_code_filter_hook‘ is hooked to the filter hook ‘the excerpt’, without determining priority, which predefined it the value 10, and without declaring number of arguments, ensuring the value for this parameter of 1. The filter hook ‘the_excerpt‘ belongs to the category of those related to reading from the publications, pages and attachments database. Applies to the summary of the posts or the content of the posts if no excerpt has been defined, which is obtained from the database, before printing on the page  

Conclusions

Hooks in WordPress are a powerful tool and constitute one of the main goals to master in the development world with this framework. To use them, you must have the code that will process the information or the code fragment that you want to execute, encapsulated in a function. The hook to which the function will be anchored must also be defined. Optionally, the number of parameters that must be passed and the priority that the method execution must have are defined. These elements are divided into 2 groups: the action hooks and the filter hooks. Action hooks do not return information and are used to execute snippets of custom code as if they were inside the WordPress core stream. Filter hooks take information before printing it on th page or saving it in the database, allow it to be processed and then return it to the code flow, so that it can be worked on if desired. Both action hooks and filter hooks are categorized into a different groups according to different criteria. Hooks are one of the most important concepts in WordPress, if you are still interested in the development of themes or plugins, I suggest the following links

How to create a plugin in WordPress?

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

Custom Post Type in WordPress (CPT)  

WordPress official doc (Hooks)

 

Custom Post Types in wordpress

Custom Post Type in WordPress (CPT)

WordPress is a wonderful CMS (Content Management System), currently a large percentage of websites are built on this platform. Its easy handling and low learning curve make users opt for this platform. But the question always arises of how to get the most out of WordPress, since this post will be directed to an important part of this technology, we will talk about CPT (Custom Post Type).

What are Custom Post Type?

Custom Post Type  in WordPress are just that, post types. We know that WordPress defines two important types of posts by default, post and page, and these are used to create posts in our blog, or to create the pages of our website. We can define a set of posts for our blog and they will be defined under certain categories that will classify the content.

Another important concept of WordPress are taxonomies, they are very linked with the CPT’s I recommend that you read this articles if you have not heard of them Taxonomies in WordPress. What are they for? How are they created?

Why do we need Custom Post Type?

The magic question would be this, what is the use of this? Well, it is very easy, the truth when WordPress arose was thinking to create blogs, that is, having a set of entries under a certain number of categories. But today this technology is used for any type of project, such as: e-commerce, a book website and even more. As they manage to create all types of content, it is just as simple, with the Custom Post Type. If we want our website to have a Portfolio, showing our work, we only have to create a Custom Post Type for it.

¿Comó crear un Custom Post Type en WordPress?

There are quick solutions like plugins that perform this task, for example Custom Post Type UI . But I always defend the idea of not using plugins for everything, that is why I leave you with some steps on how to create custom post type manually.

Always remember that the code must be in the functions.php file in your theme or the child theme (or inside of a custom plugin).

Step 1

The first step is to define a function, in my case it will be called wr_portfolio_cpt, to avoid collisions with other code it is always important to define the names of the functions with prefixes or suffixes, my theme is called Web Ready so my prefix is wr, and the CPT suffix referring to what the function defines, in this case Custom Post Type.

function wr_portfolio_cpt(){
     $labels = array(
         'name' => 'Portfolio',
         'singular_name' => 'Portfolio',
         'add_new' => 'Add Items',
         'all_items' => 'All Items',
         'add_new_item' => 'Add item',
         'edit_item' => 'Edit item',
         'new_item' => 'New Item',
         'view_item' => 'View Item',
         'search_item' => 'Search Portfolio',
         'not_found' => 'No items found',
         'not_found_in_trash' => 'No items found in trash',
         'parent_item_colon' => 'Parent Item'
     );

     $args = array(
         'labels' => $labels,
         'public' => true,
         'publicly_queryable' => true,
         'query_var' =>    true,
         'rewrite' => true,
         'capability_type' => 'post',
         'hierarchical' => false,
         'supports' => array(
             'title',
             'editor',
             'excerpt',
             'thumbnail',
             'revision'
         ),
         'taxonomies' => array('category','post_tag'),
         'menu_icon' => 'http://localhost/webready-remote/wp-content/uploads/2018/10/portfolio.png',
         'menu_position' => 5,
         'exclude_from_search' => false,
         'register_meta_box_cb' => 'wr_add_image_portfolio_metaboxes',
         'show_in_menu' => true,
         'has_archive' => true 
     );


     register_post_type('portfolio',$args);
 }

This function defines two variables ($labels, $args) and an internal function (register_post_type).

The variable $labels is an array that defines some properties that are used to define labels such as: the name with which the CPT will appear in the right menu in WordPress and other labels that you will see at the moment that you can customize.

The variable $arg is used as the second parameter of the function register_post_type(), it is like $ labels an array, and it already defines properties that are more functional like: the positions in the left menu in WordPress, or if you want to define a icon and even the elements you want this CPT to have.

Step 2

Define the hook that you created in a new CPT called portfolio.

add_action('init', 'wr_portfolio_cpt);

Conclusions

Custom Post Types are one of the key pieces of the WordPress core. Turn this CMS into a powerful tool for creating websites of all dimensions. Its use provides this platform with enormous versatility, since it does not limit it only to blogs, but to all types of projects. Currently this functionality makes WordPress have more followers and makes it the technology to follow right now. Please any questions write us or just leave a comment below.

How to create a plugin in wordpress?

How to create a plugin in WordPress?

Introduction

As is known, more than 30% of the websites in the world are created with WordPress. This means that with this web development framework more websites are generated on the planet than with any other software for this purpose. The diversity of sites that are developed with WordPress is equally wide. With this incredible tool you can create websites for any type of content. This versatility is possible precisely thanks to its status as a content management system (CMS). One of the features that most promote the use of WordPress is its plugins. The WordPress installation offers the basic foundational framework for a website. However, the functionalities can be easily extended and added by means of plugins. There are around 50,000 of them available at WordPress.org. These separate pieces of code can be added in any installation without much difficulty. In this article we are going to know what plugins are, how they are integrated into WordPress, how they work, what their structure is, and create a wordpress plugin step by step. Before creating a wordpress plugin from scratch, we will explain some concepts.

What are plugins in WordPress?

In WordPress, plugins are pieces of code that are integrated into the system and extend or add functionality. These new capabilities offer flexibility to the basic installation, so that by mastering the skills to create them, it is possible to build virtually any type of application with WordPress. Plugins are one of the most important features of this framework. In fact, they are often underlined as the best reason to use WordPress. When created for this system, they need to be written in PHP, the programming language in which WordPress is developed. Through them it is possible to add to the system a great variety of characteristics that respond to the specific needs of the domain of almost any problem. The independent developers are the ones who create the plugins. These are reviewed at WordPress.org when they are uploaded, so that way you make sure that those who follow the guidelines stay and implement good programming practices from the WordPress repository. There are free and paid plugins, in the same way that happens with themes. The decision to choose a free plugin must take into account that you have to be careful when taking this step. With this category of plugins you can run the risk of not getting help or support of any kind. Payment plugins developed by recognized organizations typically ensure you get more features, functionality, and support. Plugins can:

    • add security to the site,
    • turn it into an e-commerce with cart,
    • enhance the management system functionalities for any type of content,
    • link it to the owner’s social networks,
    • make it look better,
    • improve their performance,
    • attract more traffic,
    • protect it from malicious programs, among other various possibilities.

When installing WordPress 2 plugins are automatically added. One of them is Hello Dolly, which shows fragments of the song of the same name, by Louis Armstrong, on the dashboard. It serves as an example of how the basic structure of the plugins should be in this framework. The other one is Akismet, a plugin that adds security to the site, keeping at bay the spam content that is sometimes added by bots. The plugins ensure that the functionalities that provide the installation of WordPress are maintained in the system even when changing the subject. As separate pieces of code that add to the workings of the WordPress core, they are modularly separated from it, and can be added or removed at any time. In a multi-site configuration, adding plugins to the parent installation shares the functionalities provided by this plugin for the installation network.

How do plugins work?

Plugins are supported by WordPress hooks. As explained in this post, hooks allow you to anchor custom code snippets to different parts of the WordPress core. In this way the developer can extend the core functionalities to make the system what he wants or needs. Hooks fall into two categories:

  • action hooks: allow to add or modify functionalities in WordPress
  • filter hooks: allow to redefine WordPress functionalities

The WordPress documentation on hooks contains all the information necessary to learn how to work with them. It is important to know most or at least the most important ones and when they are executed, in the case of a beginning developer. Plugins should be located in the / wp-content / plugins / folder, in their own directory, with the name determined by the developer. The name of the plugin directory must be unique so as not to conflict with another plugin that could have the same identifier. Underscores and underscores and spaces in the name of a plugin directory should be avoided. In turn, the main file should be named the same as the folder that contains it. A good strategy for shaping the identifier might be to match the name of the company or developer and a short description of the functionality it contains. For example, if the company is named WordPress Solutions and has created a moon travel plugin, the plugin folder could be identified as wps-moon-travel and the main file within the plugin would be named wps-moon-travel.php .

Another important consideration about plugins is security, as it does not provide vulnerable access mechanisms to the websites where the plugin is installed. Likewise, creating the plugin documentation is essential to offer the possibility for other developers to extend and improve the plugins that we conceive. Among the files that a plugin must contain, it is necessary to have at least one PHP file that would be the main one. The module could also contain JavaScript code files, CSS, images, other PHP libraries and files for the language. There is a bibliography that recommends the following configuration for files within the plugin (/ wp-content / plugins / my-plugin):

  • /adminpages /: The files that are the pages to display in the WordPress control panel for the plugin  are stored in this address
  • /classes /: The class definitions for the plugin are stored in this folder
  • /plugins / my-plugin / css /: The CSS styles included in this folder should be divided between admin.css for the administrative page and frontend.css for the page to be displayed to the user. In this folder you can include the CSS files that are needed to support a JavaScript library added to the plugin
  • /css/admin.css
  • /css/frontend.css
  • /js : JavaScript files that are necessary to provide functionality in the frontend to the plugin should be added in this folder. Likewise, here you can include or separate the designated JavaScript functions for each related party in admin.js and frontend.js files
  • /images /: Includes the images that the plugin will need
  • /includes /: Stores any type of PHP file that needs to be added to the plugin other than the main file, which must be the only file PHP at the root of the plugin. This can be the case of the functions.php , common.php or helpers.php files, which are almost always added as a standardized procedure in WordPress plugins. Small PHP scripts that accomplish simple plugin tasks can also be stored in this folder
  • /includes/functions.php
  • /includes / lib /: This incorporates third-party libraries that provide functionality for the plugin
  • /pages /: Store PHP files for the frontend
  • /services /: The PHP files for AJAX calls are located at this address
  • /scheduled /: Save PHP scripts related to scheduled tasks or features that should be executed at time intervals
  • /mi-plugin.php: This is the main plugin file. If the plugin’s functionalities require it, from a design point of view, it is possible to keep several files in addition to the main one, which would contain other functionalities, according to the design and the organizational needs of the developer. Normally in these cases the main file contains comments on the other files that would hold the code, in addition to include statements and constant definitions.

  • /my-plugin.php: Archivo principal PHP de la extensión
  • /uninstall.php: Archivo de desinstalación del plugin
  • /js/: Directorio para los archivos JavaScript
  • /css: Carpeta para los archivos de estilo CSS
  • /includes: Directorio para otros archivos del plugin como librerías
  • /images: Carpeta para las imágenes que usa el plugin

Keeping the plugin files organized in a clear hierarchy can make a big difference in productivity in the development of other plugin versions over time. In the same way you can help other developers to continue with the logic of the extension when they review the plugin code. Plugins can provide functionality that is useful or necessary for a WordPress installation. Each plugin can contain its own hooks, which would allow any developer to build extensions on top of other plugins. In the same way that WordPress hooks are used, it is possible to use the hooks of other plugins.

Code conventions and good practices

In WordPress the kernel is written in such a way that it follows certain standards to respect a style and keep the code readable, uniform, clean and consistent.

Plugin and theme developers should follow these standards when creating code for the platform as this maintains consistency between core code, plugins, and themes.

The standards can be consulted in the official WordPress documentation at http://codex.wordpress.org/WordPress_Coding_Standars.

In general, it is necessary to document the code of the functions declaring a brief description, first, then a deeper description and finally expose the types, names and descriptions of the parameters and the value that is returned, if applicable. Likewise, variables, functions and files must follow a certain convention to be named, written in lower case, with words separated by underscores; and in the code use single quotes whenever possible.

To increase the readability of the code, it should be embedded in logical structures such as loops, conditions and functions, using the real tab and not spaces. Another recommendation to follow is to use the brace style in the code. This means that the opening parentheses must remain on the line, for example, of the conditional statement to which it belongs, and the closing parentheses on a separate line.

Commenting on the end of a very long code block is also good practice, because it makes it easier to read; And of course, the spaces in the code must follow the commas and exist on both sides of the logical or assignment operators. Something that is highly recommended to do when developing plugins is to establish a prefix that is taken into account to name any element that conforms to the extension. In the case that was presented, wrn should not only go in the name of the directory and the main file, but also in the names of the functions inside the plugin and the variable names that are used in the code.

This practice allows you to avoid surprises in the execution of WordPress, because without intention we could name a variable with the same identifier as another one in the core of the system and without a doubt that is not desirable. A good idea to make prefixes might be to use the initials of the programmer and the initials of the extension being developed.

To the previous conventions we must add the use of the standard PHP tags (<? Php to open a block of code or PHP file and?> To close), discarding the shortcuts <? and?> that can cause problems on many servers.

Creating a plugin for the first time

To develop a plugin you need to make sure that you can access the WordPress installation you are working with, specifically the directory where the plugins are stored, / wp-content / plugins /.

It is recommended to work with a test installation, in order to protect any production system from possible errors that arise during the development of the plugin.

In the folder where the plugins are stored, create the directory that will contain the plugin that will be developed. It will be named as the plugin. In our case, a very simple plugin will be created in order to learn the basic and fundamental steps when generating new plugins. We will focus on the good practices that it is recommended to follow in the plugin creation process. The first thing to consider is the consistency of the name of the plugin directory with the plugin itself.

As already explained, it is necessary to name the folder that stores the plugin in the same way as the main file of the plugin. Although it is true that you can create a plugin that works with a simple PHP file, directly contained in the plugins folder, it is best to create a directory that contains the main file and other elements that may need to be added in the development process. of the same. The extension we will create will simply take the content of the excerpt of the entries and change them for a short text.

Given the fact that our goal is to learn the basics of creating plugins, there is no need to implement something complex. Making use of the hook facilities to add a little example functionality is enough. We will name the folder that contains the plugin with the identifier wrn-my-first-plugin, and the main file, if we follow the good practices, will be designated as wrn-my-first-plugin.php. Once the plugin directory and its main PHP file have been created, we proceed to edit the latter. In this step it is important to know that the main file of a plugin must contain certain information related to it, that WordPress shows the user who installs the extension on their website. This information is declared within a multiline comment at the beginning of the main file. The plugin header is the only requirement that exists for it to work in WordPress.

This block indicates to the system that the extension is valid. At least the plugin name must be added in the header, so that it can be recognized by the framework. However, it is good practice to include the other elements that make up the block. The following code snippet is the complete example of our plugin:

<?php 
    /**
     * Plugin Name: WebReadyNow - My first plugin
     * Plugin URI: https://ebreadynowcom.stage.site/plugins/mi-primer-plugin
     * Description: This is a test plugin to show how importan they are
     * Author: Carlos Ernesto Velazquez Rodriguez
     * Version: 1.0.0
     * Author URI: https://ebreadynowcom.stage.site/
     * License: GPL-2.0+
     * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
     */

    #region Archivo: /wp-content/plugins/my-plugin/my-plugin.php

    /**
     * Return predifined text
     * 
     * this function return html block
     * 
     * @return  html block
     */
    function wrn_my_filter_hook_code( ) {
        $wrn_excerpt_text = '<i>Custom code linked to  \'the_excerpt\'</i> hook<br><br>';
       
        return $excerpt_text;
    }

    // Filter Hook
    add_filter('the_excerpt', 'wrn_my_filter_hook_code');
    
    #endregion
?>

The elements included in the plugin header are described below:

  • Plugin Name: Plugin’s name
  • Plugin URI: The address where the plugin can be found
  • Description: Plugin’s description
  • Version: Plugin’s version
  • Author: Plugin’s author name
  • Author URI: Plugin’s author url
  • License: Plugin’s license

The functionality of the plugin that is presented is very simple. It consists of changing the summary of the posts by the text Custom Code anchored to the filter hook ‘the_excerpt’, showing it in italics. When activating the plugin, every time the_excerpt() function is called in the active theme or template, instead of the text that is stored in the database for each abstract of each article, the text shown above will be displayed.

Conclusions

WordPress plugins are a powerful tool as they add developer-created functionality to the core of the system, enriching and adapting it to the needs of different and broad groups of software developers. This versatility makes WordPress the adaptable system it is, which, among other benefits, allows this CMS to enjoy the popularity it has to date, making it the most widely used framework for creating applications and websites throughout the world. planet. The plugins in this system are located in the / wp-content / plugins / folder, and it is where they must be copied directly so that they appear in the Plugins section, where you will have the possibility to install, uninstall, activate, deactivate or eliminate them on the platform. A plugin must minimally contain a main PHP code file with its name. Ideally, all extensions should include within a directory all the files that make them up, such as images, CSS style files or JavaScript codes. A multi-line comment block must be included in the header of the main plugin file. In this section it is necessary to specify at least the name of the plugin so that WordPress recognizes it as such. Other information that should be added for good practice are the description of the functionalities that the plugin solves, the name of the author, a reference web address of the plugin and the author, the version of the plugin and the name of the license under which it is used. create the plugin. Plugins work by taking advantage of the hooks provided by the WordPress core, and in turn they can register new hooks themselves to allow other plugins to extend their functionality and further enrich the system. Like all well written code, WordPress plugins must follow defined standards to maintain a certain homogeneity, readability and consistency. From that approach, WordPress extensions must follow the code standards that WordPress core itself follows. We hope this article has helped you get started in the world of WordPress plugin development, which is a first step in creating systems based on your own needs or those of your future clients. If it has served you, share it on your social networks to help others learn more about this incredible system that is WordPress.

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.