search
HomeBackend DevelopmentPHP TutorialCustom Plugins: A Comprehensive Guide to WordPress Taxonomies for Beginners

In this series, we’ve been looking at WordPress taxonomies: what they are, how they work, how to distinguish the different types that exist, and how they are stored in the underlying database. p>

The only thing we have to do is assemble a plugin that demonstrates how to use the API to implement our own custom taxonomies. So, in this article, we will do exactly that.

Recall the first article in this series:

Classification is one of those words that most people have never heard of or used. Basically, a taxonomy is a way of grouping things together.

Throughout this series, we have been using photography and videography as classification examples. Therefore, for the plugin we are going to build, we will include hierarchical and non-hierarchical taxonomies related to these two classifications.

  1. The hierarchical taxonomy will include the basic taxonomy of photos and videos.
  2. Non-hierarchical classification will be used to specify the film type used. This can be black and white, color, sepia, or any color you want to specify.

Finally, the plugin will work with the existing standard post types that come with WordPress. This should provide the most flexibility as it relates to building the plugin, demonstrating the concept, and using it in your own installation.

My Custom Taxonomy

For the purposes of the example plugin, we'll call it My Custom Taxonomy, and we'll build it in the following stages:

  1. We will prepare the core plugin file, which contains the correct title text needed to display the plugin in the WordPress dashboard.
  2. We will set up the code required to execute the core plugin.
  3. We will write code to introduce the Photo and Video categories.
  4. We will write code to introduce the movie genre taxonomy.
  5. Then we will test the complete plugin.

1. Plug-in header

Before doing anything else, create a directory named my-custom-taxonomies in wp-content/plugins and introduce a directory named My custom taxonomy.php.

自定义插件:针对初学者的 WordPress 分类法综合指南

Add the following code comment block to the file:

<?php
/**
 * My Custom Taxonomies
 *
 * Demonstrates how to create custom taxonomies using the WordPress API.
 * Showcases both hierarchical and non-hierarchical taxonomies.
 *
 * @link              https://code.tutsplus.com/series/the-beginners-guide-to-wordpress-taxonomies--cms-706
 * @since             1.0.0
 * @package           Custom_Taxonomies
 *
 * @wordpress-plugin
 * Plugin Name:       My Custom Taxonomies
 * Plugin URI:        http://example.com/plugin-name-uri/
 * Description:       Demonstrates how to create custom taxonomies using the WordPress API.
 * Version:           1.0.0
 * Author:            Tom McFarlin
 * Author URI:        http://tommcfarlin.com/
 * License:           GPL-2.0+
 * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt
 */

At this point, you should be able to log into your WordPress dashboard, view the name of the plugin, and activate it. Of course, nothing will actually happen because we haven't done anything to the source code yet.

Next, we need to create another file to actually power the plugin. This will be based on object-oriented programming principles, so we will create a file called class-my-custom-taxonomies.php.

Don't worry about filling it with any source code just yet. Let’s go back to my-custom-taxonomies.php and add a condition to ensure that the core plugin file cannot be run outside of the WordPress environment.

<?php

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
    die;
}

Place this directly under the code comment we provided above.

2. Execute core plug-in

At this point, we are ready to write the code that actually drives the plugin. So let's define a class and a basic function for initialization:

<?php

/**
 * The core plugin class file
 *
 * Defines the functions necessary to register our custom taxonomies with
 * WordPress.
 *
 * @link       http://code.tutsplus.com/series/the-beginners-guide-to-wordpress-taxonomies--cms-706
 * @since      1.0.0
 *
 * @package    Custom_Taxonomies
 * @author     Tom McFarlin <tom@tommcfarlin.com>
 */
class My_Custom_Taxonomies {

    /**
	 * Initializes the plugin by registering the hooks necessary
	 * for creating our custom taxonomies within WordPress.
	 *
	 * @since    1.0.0
	 */
	public function init() {

	}

}

After that, let's go back to my-custom-taxonomies.php and add code to include the file and the methods that create an instance of the class and execute it: p>

<?php

/** Loads the custom taxonomy class file. */
require_once( dirname( __FILE__ ) . '/class-my-custom-taxonomies.php' );

/**
 * Creates an instance of the My_Custom_Taxonomies class
 * and calls its initialization method.
 *
 * @since    1.0.0
 */
function custom_taxonomies_run() {

    $custom_tax = new My_Custom_Taxonomies();
	$custom_tax->init();

}
custom_taxonomies_run();

Now we have everything we need to start actually setting up hooks and callbacks to create custom taxonomies.

3. Introduction Photos and Videos

At this point, we are ready to start introducing our taxonomy. We first focus on two hierarchical taxonomies - Photo and Video.

In the class body of the class-my-custom-taxonomies.php file, add the following function:

<?php

/**
 * Creates the Photographs taxonomy that appears on all Post dashboard
 * pages.
 *
 * @since    1.0.0
 */
public function init_photographs() {

    $labels = array(
		'name'          => 'Photographs',
		'singular_name' => 'Photograph',
		'edit_item'     => 'Edit Photograph',
		'update_item'   => 'Update Photograph',
		'add_new_item'  => 'Add New Photograph',
		'menu_name'     => 'Photographs'
	);

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

	register_taxonomy( 'photograph', 'post', $args );

}

This function is responsible for creating the Photo category and will be called from the init function at the appropriate time.

Now, let’s do the same thing with video :

<?php

/**
 * Creates the Videos taxonomy that appears on all Post dashboard
 * pages.
 *
 * @since    1.0.0
 */
public function init_videos() {

    $labels = array(
		'name'          => 'Videos',
		'singular_name' => 'Video',
		'edit_item'     => 'Edit Video',
		'update_item'   => 'Update Video',
		'add_new_item'  => 'Add New Video',
		'menu_name'     => 'Videos'
	);

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

	register_taxonomy( 'video', 'post', $args );

}

Let's call these two functions in the init function. We do this by registering these functions using the init hook provided by WordPress:

<?php

public function init() {

    add_action( 'init', array( $this, 'init_photographs' ) );
    add_action( 'init', array( $this, 'init_videos' ) );

}

Here we should be able to go to Add New Post and see the new category options in the dashboard. If not, please double check your code against the code shared above.

自定义插件:针对初学者的 WordPress 分类法综合指南

Now that we've covered our hierarchical taxonomy, let's move on to our Video Types - or our non-hierarchical - taxonomy.

4。介绍影片类型

这实际上与我们到目前为止编写的代码没有太大不同。实际上,主要区别在于,我们不是将 hierarchical 指定为 true,而是将其设置为 false

<?php

/**
 * Creates the Film Type taxonomy that appears on all Post dashboard
 * pages.
 *
 * @since    1.0.0
 */
public function init_film_type() {

    $labels = array(
		'name'          => 'Film Type',
		'singular_name' => 'Film Type',
		'edit_item'     => 'Edit Film Type',
		'update_item'   => 'Update Film Type',
		'add_new_item'  => 'Add New Film Type',
		'menu_name'     => 'Film Type'
	);

	$args = array(
		'hierarchical'      => false,
		'labels'            => $labels,
		'show_ui'           => true,
		'show_admin_column' => true,
		'rewrite'           => array( 'slug' => 'film-type' )
	);

	register_taxonomy( 'film-type', 'post', $args );

}

这将导致不同类型的用户界面元素,看起来更像标签,而不是您在上面看到的类别选项。

最后,将以下行与其余钩子一起添加到 init 方法中:

<?php
add_action( 'init', array( $this, 'init_film_type' ) );

请注意,函数更像是分类标签。再次重申,这是分层分类法和非分层分类法的主要区别之一。

5。测试完整插件

现在我们准备好试用该插件了。假设您正确遵循了本教程中的所有内容,那么您应该能够创建新帖子,并使用照片类型或视频类型对其进行标记作为影片的一种类型,并在保存或更新您的帖子后保留更改。

如果没有,请根据此处引用的内容以及关联的 GitHub 存储库中引用的内容仔细检查您的代码。

结论

WordPress 分类法初学者指南到此结束。在整个系列中,我们广泛了解了分类法的定义、它们在 WordPress 中扮演的角色,甚至还实现了一些我们自己的分类法。

此时,您应该对这个概念以及如何将它们包含在您的下一个项目中有深入的了解。

如果没有,请随时在下面的字段中留下问题、评论或一般反馈。

The above is the detailed content of Custom Plugins: A Comprehensive Guide to WordPress Taxonomies for Beginners. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software