WordPress Plugin Development Tutorial Manual - Customizing Category Methods

Taxonomy is another way of saying categories and groupings, and taxonomies can be hierarchical and flat.WordPress lets plugin developers register custom taxonomies, which are stored in the term_taxonomy datasheet. The taxonomy has a number of taxonomy items that are stored in the wp_terms table. For example, a taxonomy called "Art" has multiple taxonomy items such as "Art Now" and "18th Century Art".

In this chapter, we will learn how to register a custom taxonomy, how to get the custom taxonomy content from the database, and how to display it to the user.

WordPress 3.4 and earlier had a default categorization method called "Links", which is not recommended in WordPress 3.5 and later.

Use of customized taxonomies

Customized classification methods

With the introduction of the taxonomy system, the default WordPress taxonomy methods "Categories" and "Tags" are often times no longer sufficient for our needs, and it's time to create custom taxonomies. Custom taxonomy methods are usually used in conjunction with custom post types to categorize our custom content according to our custom criteria.

Why use custom categorization

Some developers may ask why we should use taxonomies and what benefits can using taxonomies bring us? When to use taxonomies to organize content? Let's use an example to illustrate the benefits of using the taxonomy method. Let's say a client who is a chef needs us to help him create a website using WordPress to showcase his recipes.

In order to avoid mixing this type of content with other content, which can be confusing to manage, we need to create a custom article type called "Recipes" to store the content of this chef's recipes. Recipes will of course be categorized, we need to create a taxonomy called "Course" to separate the two different types of recipes, "Appetizers" and "Desserts", and then create a taxonomy called We need to create a category called "Ingredients" to categorize recipes into "Chicken" and "Chocolate" depending on the ingredients.

Of course, we can also use the default "Categories" and "Tags" to organize the content of our recipes, in which case we need to create a category called "Courses", then "Appetizers" and "Desserts" subcategories, as well as "Ingredients" category and their subcategories. In this case, we need to create a category called "Courses", then create subcategories for "Appetizers" and "Desserts", as well as a category for "Ingredients" and their subcategories.

The main advantage of using custom categories is that we can differentiate our recipes using a category system that is independent of "Categories" and "Tags", and custom categories have their own menu in the WordPress back-end, which makes them easier for It's also easier for us to manage. Additionally, creating custom categories allows us to create customized interfaces and data entry/exit processes, which reduces the learning and usage costs for our users. If we create a custom taxonomy in the plugin, we can also reuse it on different WordPress sites.

Example: Course Classification Methodology

The following example will show how to create a custom taxonomy "Course" and add this custom taxonomy to the default "Article" post type. Before attempting to create the plugin, make sure you read thePlugin Development BasicsChapter.

Step 1: Before you start

Open up:Articles>Writing Articles page, we can see that by default there are two categorization methods: Categorized Catalog and Tags.

Step 2: Create a new plugin

Use the init Action hook to register a custom taxonomy method "Course" for the content type "Article".

/*
* Plugin Name: Course Taxonomy
* Description: A short example showing how to add a taxonomy called Course.
* Version: 1.0
* Author: developer.wordpress.org
* Author URI: https://codex.wordpress.org/User:Aternus
*/

function wporg_register_taxonomy_course() {
   $labels = [
      
      'singular_name' => _x( 'Courses', 'taxonomy singular name' ),
      'search_items' => __( 'Search Courses' ),
      'all_items' => __( 'All Courses' ),
      'parent_item' => __( 'Parent Courses' ),
      'parent_item_colon' => __( 'Parent Course:' ),
      'edit_item' => __( 'Edit Course' ),
      
      
      'new_item_name' => __( 'New Course Name' ), 'menu_name' =>
      'menu_name' => __( 'Course' ), .
   ];
   $args = [
      'hierarchical' => true, // make it hierarchical (like categories)
      'labels' => $labels, // make it hierarchical (like categories).
      'show_ui' => true, // make it hierarchical (like categories)
      'show_admin_column' => true, // make it hierarchical (like categories)
      
      'rewrite' => [ 'slug' => 'course' ], .
   ];
   register_taxonomy( 'course', [ 'post' ], $args );
}

add_action( 'init', 'wporg_register_taxonomy_course' );

Step 3: View Results

Activate the plugin we just created and open theArticles>Writing Articles page, and if all goes well, we'll see a taxonomy named "Courses".

Code Interpretation

Let's go through the functions and parameters used to implement the above functionality one by one.

Function wporg_register_taxonomy_course All the steps needed to register a custom article type.

$label The data defines the labels for the custom taxonomy, which is the name, action, and various other information about the taxonomy that we see in the backend.

$args The parameters contain the configuration options used when creating a custom taxonomy, and are used to instruct WordPress on how to set up a custom taxonomy.

register_taxonomy() The function uses the $args array to configure a course classification method for the content type "Article".

add_action() function binds the creation of the category method to the init Action hook.

summarize

With our sample code for creating a "Courses" taxonomy, WordPress will automatically create an archive page and its child pages for the "Courses" taxonomy.

The custom taxonomy archive page takes the form (/course/%%term-slug%%/), of which /course/ is the identifier of the custom taxonomy.%%term-slug%% Alias for the classification item in the custom classification method.

Use of customized taxonomies

There are many functions in WordPress to manipulate custom taxonomies and the categorized items in custom taxonomies. Such as:

  • the_terms: Accepts taxonomy parameters and displays taxonomy items in a list.
  • wp_tag_cloud: Accepts taxonomy parameters and displays taxonomy items as a tag cloud.
  • is_taxonomy: Determines if it is the specified categorization method.

Split Taxonomy Project (WordPress 4.2+)

WordPress 4.2 and earlier

Prior to WordPress 4.2, the same taxonomy items used in different taxonomies would share a taxonomy item ID, e.g. taxonomies and tags with the same alias "news" shared an ID, when in fact they were one taxonomy item.

WordPress 4.2 onwards

Developed from WordPress 4.2, when these shared taxonomy items are updated, they are split into separate items, each assigned a new ID.

What does that mean?

In the vast majority of cases, this update is seamless and smooth, however, some plugins and themes store some taxonomy IDs into options, post_meta, user_meta, or other data, and in these cases, the theme or plugin may be affected.

Handling of taxonomy project splits

WordPress 4.2 provides two impassable tools to help plugin and theme developers make the switch.

split_shared_term hook

If a shared taxonomy item is assigned a new ID, the mount to the split_share_term hook is automatically triggered. Below is an example of a theme and plugin developer using this hook to ensure that the stored taxonomy item ID is updated.

Stored in Options

Suppose our plugin stores an option called feartured_tags, which contains an array of tag IDs ( [4,6,10] ) that are query parameters for the homepage Featured Articles module. In this example, we'll mount a function to the split_shared_term Action hook that will check to see if the tag IDs are in the array and update the array if necessary.

/**
 * Update featured_tags option when a shared term gets split.
 /** * Update featured_tags option when a shared term gets split.
 * @param int $term_id ID of the formerly shared term.
 * @param int $new_term_id ID of the new term created for the $term_taxonomy_id.
 * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split.
 * @param string $taxonomy Taxonomy for the split term.
 */ @param string $taxonomy_taxonomy for the split term.
function wporg_featured_tags_split( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
   // we only care about tags, so we'll first verify that the taxonomy is post_tag.
   if ( $taxonomy === 'post_tag' ) {

      // get the currently featured tags.
      $featured_tags = get_option( 'featured_tags' );

      // if the updated term is in the array, note the array key.
      $found_term = array_search( $term_id, $featured_tags ); if ( $found_term ); // If the updated term is in the array, note the array key.
      if ( $found_term ! == false ) {

         // The updated term is a featured tag! replace it in the array, save the new array.
         $featured_tags[ $found_term ] = $new_term_id; update_option( 'featured_tags' ); if ( $found_term !
         update_option( 'featured_tags', $featured_tags );
      }
   }
}

add_action( 'split_shared_term', 'wporg_featured_tags_split', 10, 4 );

Stored in post_meta

Suppose, the plugin saves a tag ID for the page, by which we can display related posts in the post page. In this case, we use the get_psots() function to get the pages that match the meta_key and meta_value, and then update the meta_value to the split ID.

/**
 * :: Update related posts term ID for pages
 /** * Update related posts term ID for pages.
 * @param int $term_id ID of the formerly shared term.
 * @param int $new_term_id ID of the new term created for the $term_taxonomy_id.
 * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split.
 * @param string $taxonomy Taxonomy for the split term.
 */ @param string $taxonomy_taxonomy for the split term.
function wporg_page_related_posts_split( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
   // Find all the pages where meta_value matches the old term ID.
   $page_ids = get_posts( [
      
      
      
      'meta_value' => $term_id, .
   ] );

   // if such pages exist, update the term ID for each page.
   if ( $page_ids ) {
      foreach ( $page_ids as $id ) {
         update_post_meta( $id, 'meta_key', $new_term_id, $term_id ); }
      }
   }
}

add_action( 'split_shared_term', 'wporg_page_related_posts_split', 10, 4 );

wp_get_split_term function

Using the split_shared_term hook is the preferred way to handle taxonomy item ID changes. However, there may be cases where the plugin does not have a chance to execute the split_shared_term hook.

WordPress saves the split taxonomy item information and provides the wp_get_split_term() function to help developers get this information.

Consider the above scenario, our plugin stores an array of options called feartured_tags with the value of taxonomy item IDs, we may need to create a function to check if these IDs (which can be updated when the plugin is updated) contain the IDs that have been split, and if they do, we will need to update the IDs of the taxonomy items after they have been split to this array.

function wporg_featured_tags_check_split() {
   $featured_tag_ids = get_option( 'featured_tags', [] );

   // check to see whether any IDs correspond to post_tag terms that have been split.
   foreach ( $featured_tag_ids as $index => $featured_tag_id ) {
      $new_term_id = wp_get_split_term( $featured_tag_id, 'post_tag' );

      if ( $new_term_id ) {
         $featured_tag_ids[ $index ] = $new_term_id;
      }
   }

   // save
   update_option( 'featured_tags', $featured_tag_ids );
}

Note that wp_get_split_term() takes two arguments.$old_term_id respond in singing $taxonomy and returns an integer.

If we need to get a list of split taxonomy items in all taxonomies associated with an old taxonomy ID, we can use the wp_get_split_terms() function The

We offer WordPress Themes and Plugins Custom Development Services

This site has long undertaken WordPress themes, plugins, WooCommerce-based store mall development business. We have 10 years of experience in WordPress development, if you want to Developing Websites with WordPress, please contact WeChat: iwillhappy1314 or email: amos@wpcio.com for inquiries.

1 thoughts on “WordPress插件开发教程手册 — 自定义分类方法

发表回复

Your email address will not be published. 必填项已用 * 标注

*