作者都是各自领域经过审查的专家,并撰写他们有经验的主题. 我们所有的内容都经过同行评审,并由同一领域的Toptal专家验证.
Rodrigo Donini
Verified Expert in Engineering

Rodrigo has 17 years of experience in web and mobile projects. He has a strong knowledge base of the WordPress world.

Expertise

PREVIOUSLY AT

CWI Software
Share

WordPress, 最强大的开源博客和内容管理系统之一, is being used to power a major chunk of the interwebs. 多达四分之一的网站运行WordPress,而且对WordPress的需求并不短缺 WordPress development services.

与许多其他cms不同,WordPress因其灵活性和可定制性而受到许多人的喜爱. Taxonomies, one of the core features of WordPress, allows you to organize content just the way you need to. Although it comes built-in with a few default taxonomies, WordPress lets you add as many custom taxonomies as you please.

However, 要使分类法完全按照您所希望的方式运行,可能需要使用一些未记录的方法.

Graphic representation of the various WordPress taxonomy options

In this article, 你将学习如何在WordPress中定义专属自定义分类法,它的行为更像类别而不是标签, 允许你对你的帖子进行更严格的分类.

What Is a Taxonomy?

According to the WordPress codex:

A taxonomy is a way to group things together.

For example, 一堆不同种类的水果可以根据不同的特征分组,然后这些组可以分配名称.

In WordPress, taxonomies are used to group posts, pages, and even custom post types under different groups.

The names for the different groupings in a taxonomy are called terms. 以水果为例,以及如何根据它们的颜色对它们进行分组. In this case, the names of different colors would be the terms.

By default, WordPress comes built in with four taxonomies: category, tag, link category, and post format. You can learn more about these default taxonomies here.

Among these built-in taxonomies, 类别和标签非常相似,但有一个重要的区别:类别是排他性的分类法(即.e., for each post, 您最多可以选择一个类别,而每个帖子可以分配多个标签.

此外,类别通常是预定义的,而标签可以随您的发展而定义.

Defining Custom Taxonomies

You can define a custom taxonomy using the register_taxonomy() function. You can learn more about the function here.

为了了解这个函数是如何工作的,让我们为带有风景照片的帖子定义一个自定义分类法.

function view_init() {
	register_taxonomy(
		'view',
		'post',
		array(
			'label' => __( 'View' ),
			'capabilities' => array(
				'assign_terms' => 'edit_guides',
				'edit_terms' => 'publish_guides'
			)
		)
	);
}
add_action( 'init', 'view_init' );

In the above snippet, we are defining a new taxonomy for posts called view.

您可以将这种分类法用于根据照片中呈现的视图的类型或性质对照片进行分类(例如.g., mountain, lake, or forest).

与往常一样,属于此类别的特定条款的帖子将出现在 /view/{view_name}.

The capabilities line in the snippet above is optional. 如果没有它,WordPress将默认向与帖子相同的用户提供功能. As shown above, 这将允许任何具有自定义“edit_guides”功能的用户将分类法分配给帖子,允许任何具有自定义“publish_guides”功能的用户创建新的分类法项.

根据官方文档,可以定义四种功能:

Taxonomy capabilities include assignterms, editterms, manageterms (displays the taxonomy in the admin navigation) and deleteterms.

How Taxonomies Are Used

Within your code, you can use the wp_set_object_terms() function to add terms to objects using the taxonomy. You can list existing terms using the the_terms() function. Furthermore, you can use the wp_tag_cloud() function to generate a cloud of terms for your custom taxonomy. You can learn more about these functions here.

在UI方面,WordPress为每个分类在帖子上创建一个新的元框. 元框类似于标签元框,它允许你将一个或多个术语链接到你的文章. This is what WordPress does by default, 这就是我们可以通过使分类法排他性来改变的:使自定义分类法的行为与类别分类法相似.

Forcing Exclusiveness on Taxonomies

When we create a custom taxonomy with the register_taxonomy() 方法,WordPress在后期编辑页面添加了一个可选择多个项目的元框:

Using this meta box, 用户可以选择任意数量的现有(已使用)术语,也可以使用文本框添加新术语.

To create a category-like taxonomy, 每个帖子最多属于一组预定义类别中的一个类别, you can do so by tweaking WordPress a little:

  • Hide the default meta box created by WordPress.
  • 在后期编辑页面上创建一个自定义元框,它将为单个项目选择提供控制.
  • Save the taxonomy value when the post is saved.

Let’s take a look at each of the steps.

Hide the Default Meta Box Created by WordPress

For this, we need to set show_in_quick_edit and meta_box_cb options to false when calling register_taxonomy.

自定义分类法元框的屏幕截图,您可以在其中向可用术语集添加项

第一个选项将分类法隐藏在快速/批量编辑面板中,第二个选项将分类法隐藏在后期编辑页面中:

register_taxonomy( 'custom_taxonomy', 'post', array(
	'labels' => array(
		'name' => 'Custom Exclusive Taxonomy'
	),
	'show_in_quick_edit' => false,
	'meta_box_cb' => false
));

When the default meta box is hidden, 可以通过分类法管理页面将条目添加到分类法的可用术语集中:

带有几个单选按钮的名为Custom Exclusive Taxonomy的元框的屏幕截图

Create a Custom Meta Box on the Post Editing Page

To create a custom meta box, we can use the add_meta_boxes WordPress hook. You can learn more about the hook here.

add_action('add_meta_boxes', 'add_custom_meta_box');
function add_custom_meta_box(){
	add_meta_box( 'taxonomy_box', __('Custom Exclusive Taxonomy'), 'fill_custom_meta_box_content', 'post' ,'side');
}

We call the add_meta_box method with the following arguments:

  • taxonomy_box – The ID of the meta box
  • __('Custom Exclusive Taxonomy') – The title of the meta box
  • fill_custom_meta_box_content – A function that is used to fill the contents of the meta box
  • post -这表明元框应该出现在后期编辑页面.
  • side – This indicates the place where the meta box should be inserted.

Notice how we specified taxonomy_box as the ID. 然而,第三个参数中的函数将让我们定义将进入框中的内容.

We will now implement the fill_custom_meta_box_content function:

 'custom_taxonomy',
		'hide_empty' => false // Retrieve all terms
	));

	// We assume that there is a single category
	$currentTaxonomyValue = get_the_terms($post->ID, 'custom_taxonomy')[0];
?>
	

Choose taxonomy value

term_id==$currentTaxonomyValue->term_id) echo "checked"; ?>>

Here, we are first retrieving all of the terms (i.e., existing values) of the taxonomy. We will use these to show a list of radio button controls.

Next, we retrieve the currently selected taxonomy term using get_the_terms() function—we need it to make the respective radio button selected.

Notice that this function returns an array. 这是因为,在默认情况下,帖子可以有任意数量的相关术语. 根据我们的假设,post最多有一个项,因此我们访问第一个数组元素. (It is ok if the array is empty; we’ll get null as the current value and no radio button will be selected.)

The HTML emitting code uses custom_taxonomy as the name of radio buttons and corresponding term IDs as their values; radio button ID attributes are just used for connecting to label tags. As a result, we get the following custom meta box:

Screenshot of Custom Exclusive Taxonomy's "add new tag" feature now available on the WordPress dashboard sidebar

Save the taxonomy Value When the Post Is Saved

Finally, we need to persist the taxonomy value when the post is saved. For this, we can use the save_post hook:

add_action('save_post', 'save_custom_taxonomy');

function save_custom_taxonomy($post_id){
	if ( isset( $_REQUEST['custom_taxonomy'] ) ) 
		wp_set_object_terms($post_id, (int)sanitize_text_field( $_POST['custom_taxonomy'] ), 'custom_taxonomy');
}

And that’s it! We are done.

现在您知道了如何定义一个自定义分类法,使其行为与内置的类别分类法类似.

Note: WordPress has accepted a feature request to make it easier to toggle exclusivity for custom taxonomies. However, the ticket has not seen much activity for a while.

Wrap Up

Taxonomies are a very powerful and useful feature in WordPress. Out of the box, they lack the ability to make strict categorization of posts, but as with nearly anything in WordPress, taxonomies and related functionality are extremely customizable. This allows us to add this often necessary ability in a few steps.

这里介绍的方法还可以用于在编辑后的页面上为分类法术语选择创建更自定义的UI.

我希望这个关于定义独占自定义分类法的快速教程对您有所帮助!

Understanding the basics

  • What is a WordPress taxonomy?

    In WordPress, 分类法是一种根据具有共同特征的不同术语对帖子和页面进行分组的方法.

Hire a Toptal expert on this topic.
Hire Now
Rodrigo Donini

Rodrigo Donini

Verified Expert in Engineering

São Leopoldo - State of Rio Grande do Sul, Brazil

Member since December 12, 2016

About the author

Rodrigo has 17 years of experience in web and mobile projects. He has a strong knowledge base of the WordPress world.

作者都是各自领域经过审查的专家,并撰写他们有经验的主题. 我们所有的内容都经过同行评审,并由同一领域的Toptal专家验证.

Expertise

PREVIOUSLY AT

CWI Software

World-class articles, delivered weekly.

By entering your email, you are agreeing to our privacy policy.

World-class articles, delivered weekly.

By entering your email, you are agreeing to our privacy policy.

Toptal Developers

Join the Toptal® community.