WordPress术语Meta和WP_Term简介
In WordPress, you can easily save metadata for your posts, pages and other custom content types, however saving metadata for use with your taxonomies used to be an overly complex process (I even wrote a previous article about it here!).
在WordPress中,您可以轻松地为帖子,页面和其他自定义内容类型保存元数据,但是保存元数据以用于分类法曾经是一个过于复杂的过程(我什至在此之前写过一篇文章! )。
To get it all to work you would need to save your term metadata as a field inside your wp_options
table for each piece of data, meaning potentially you could have hundreds, if not thousands of extra entries if you had a decent amount of terms or just several customized taxonomies.
为了使所有功能正常工作,您需要将术语元数据保存为wp_options
表中每个数据段的字段,这意味着如果您有相当数量的术语,或者仅包含相当数量的术语,则可能会有数百个(如果不是成千上万个)额外条目几种定制的分类法。
However, since WordPress 4.4 and beyond, terms are now objects, the same as posts, pages and custom content types. This change makes it much easier to add, remove and update your metadata.
但是,由于WordPress 4.4及更高版本 ,术语现在是对象,与帖子,页面和自定义内容类型相同。 此更改使添加,删除和更新元数据变得更加容易。
带有术语元的背景故事 (The Backstory with Term Meta)
The community has been pushing for an easy way to control term metadata since way back in WordPress 2.8. It’s been a slow process, but finally terms have been re-designed from the ground up to use a class structure. This plus a few different changes in WordPress 4.4 means that terms in a taxonomy (such as ‘tags’, ‘categories’ or custom) can now have their own meta easily assigned to them.
自WordPress 2.8以来,社区一直在寻求一种控制术语元数据的简便方法。 这是一个缓慢的过程,但最终术语已经完全重新设计以使用类结构。 加上WordPress 4.4中的一些不同更改,意味着分类法中的术语(例如“标签”,“类别”或自定义)现在可以轻松地为其分配自己的元数据。
旧数据元数据处理 (Metadata Manipulation the Old Way)
Before WordPress 4.4 there was no clear-cut way to easily save metadata for term items, this was an inherent limitation on terms from how it was constructed. If you were extending taxonomies or terms you would have to save your data directly as a site option using update_option
. This wasn’t ideal (as it cluttered up the options table).
在WordPress 4.4之前,尚没有明确的方法来轻松保存术语项的元数据,这是术语构造方面的固有限制。 如果要扩展分类法或术语,则必须使用update_option
将数据直接保存为站点选项。 这并不理想(因为它使选项表杂乱无章)。
I’ve written about extending taxonomies before, however the basics of it was when you were ready to save your metadata you would call a function that looked somthing like this:
我之前曾经写过关于扩展分类法的文章 ,但是它的基础是当您准备保存元数据时,您将调用一个看起来像这样的函数:
//saving new fields for category
function save_extra_taxonomy_fields($term_id){
$term = get_term($term_id);
$term_slug = $term->slug;
//collect category image id from posted values
$term_category_image_id = isset($_POST['category_image_id']) ? sanitize_text_field($_POST['category_image_id']) : '';
//update value and save it as an option
update_option('category_image_id_' . $term_slug, $term_category_image_id);
}
add_action('create_category','save_extra_taxonomy_fields');
In the above example we execute the function attached to the create_category
hook (that triggers when we create a new category term). This will look for our value and after sanitizing will save it as an option. While this works it’s not very pretty.
在上面的示例中,我们执行附加到create_category
挂钩的函数(当我们创建新的类别术语时触发)。 这将寻找我们的价值,消毒后会将其保存为选项。 虽然这个方法不是很好。
添加,更新和删除术语元 (Adding, Updating and Removing Term Meta)
To work with term meta you will use the add_term_meta
, update_term_meta
and delete_term_meta
functions. These functions when combined with new UI elements will let you save and update new metadata for your terms.
要使用term meta,您将使用add_term_meta
, update_term_meta
和delete_term_meta
函数。 这些功能与新的UI元素结合使用时,将使您可以保存和更新术语的新元数据。
添加术语元 (Adding Term Meta)
Adding metadata for a term involves the add_term_meta
function. You need to specify three parameters with an optional fourth.
添加术语的元数据涉及add_term_meta
函数。 您需要指定三个参数,第四个参数是可选的。
-
$term_id
– ID of the term you want to save this metadata to$term_id
–您要将元数据保存到的术语的ID -
$meta_key
– Key name of the metadata. This is how you will reference the data$meta_key
–元数据的**名称。 这是您参考数据的方式 -
$meta_value
– The data itself (remember to sanitize)$meta_value
–数据本身(记住要清理) -
$unique
(optional) – If the metadata key should be unique. By default this is set tofalse
and means that if another key has the same name the function it will override it. Set this totrue
to ensure uniqueness.$unique
(可选)–元数据**是否唯一。 默认情况下,此参数设置为false
,表示如果另一个键具有相同的名称,则该函数将覆盖它。 将其设置为true
以确保唯一性。
As an example imagine that for each term in our category
taxonomy we want to assign a new piece of metadata based on how many posts are assigned to this category. With WordPress 4.4 we can loop through all of the terms and save this new metadata (for use later in our theme or plugins).
举例来说,想象一下,对于category
分类法中的每个术语,我们都希望基于分配给该类别的帖子数来分配新的元数据。 使用WordPress 4.4,我们可以遍历所有术语并保存此新的元数据(稍后在我们的主题或插件中使用)。
function add_featured_to_categories(){
//get all terms from the category taxonomy
$taxonomy_name = 'category';
$term_args = array(
'orderby' => 'name',
'hide_empty' => false,
'fields' => 'ids'
);
$terms = get_terms($taxonomy_name, $term_args);
if($terms){
$term_key = 'term_size';
$term_value = 'empty';
$term_unique = true;
//go through all terms and set the new term meta
foreach($terms as $term_id){
$term = get_term($term_id, $taxonomy_name);
$term_count = $term->count;
//determine new meta value
if($term_count > 10){
$term_value = 'big';
}else if($term_count >= 5 && $term_count < 10){
$term_value = 'medium';
}else if($term_count >= 1 && $term_count < 5){
$term_value = 'small';
}
//save meta value
add_term_meta($term_id, $term_key, $term_value, $term_unique);
}
}
}
add_action('init', 'add_featured_to_categories');
阅读词元 (Reading Term Meta)
We can read saved term meta by using the get_term_meta
function. This function works in a similar way to the get_post_meta
function that is used to get metadata from posts. To use this function to need to specify one mandatory parameter, with an optional two parameters available.
我们可以使用get_term_meta
函数读取保存的术语元。 此函数的工作方式类似于用于从帖子获取元数据的get_post_meta
函数。 要使用此功能,需要指定一个强制性参数,并提供两个可选参数。
-
$term_id
– The ID of the term to fetch metadata from$term_id
要从中获取元数据的术语的ID -
$key
(optional) – A single specified key you want to return. If not specified then all metadata is returned.$key
(可选)–您要返回的单个指定**。 如果未指定,则返回所有元数据。 -
$single
(optional) – If a single value will be returned or a key or value pair. Defaults to a single value.$single
(可选)–如果将返回单个值或键或值对。 默认为单个值。
Let’s look at another scenario where you might find this useful.
让我们看另一种可能有用的场景。
Consider a situation in which we already have term meta saved for each of our terms in our category
taxonomy. This saved data contains the URL to an image that should be displayed when we are viewing the term. We want to display this image as a banner below our term description or title, but above our listing of posts.
考虑一种情况,在该情况下,我们已经为category
分类法中的每个术语保存了术语元。 此保存的数据包含当我们查看术语时应显示的图像的URL。 我们希望将此图片以横幅形式显示在术语描述或标题下方,但在帖子列表上方。
//given a term, collect its saved image to be displayed
function display_term_meta_image($term_id, $term_taxonomy){
//get supplied term
$term = get_term($term_id, $term_taxonomy);
if($term){
$term_image_id = get_term_meta($term_id, 'term_image_id', true);
if($term_image_id){
//get the medium image size for display
$term_image = wp_get_attachment_image_src($term_image_id, 'medium', false);
echo '<img src="' . $term_image[0] . '" title="' . $term->name . ' image"/>';
}
}
}
Now inside our category.php
or other child theme template file, we can modify the functionality where our term data is displayed.
现在,在category.php
或其他子主题模板文件中,我们可以修改显示术语数据的功能。
In my situation with Twenty Fourteen
I’m editing the category.php
file and calling our new function right after the display of the terms description info.
在Twenty Fourteen
情况下,我正在编辑category.php
文件,并在显示术语描述信息之后立即调用我们的新函数。
//get the current object (term)
$term_obj = get_queried_object();
//display meta data image for term
if(function_exists('display_term_meta_image')){
display_term_meta_image($term_obj->term_id, $term_obj->taxonomy);
}
This will display our photo right under the description like this:
这将在如下描述下显示我们的照片:
删除术语元 (Deleting Term Meta)
We can remove term metadata just the same as we could for posts. When we use the delete_term_meta
function we need to supply two mandatory parameters with an option third if we require.
我们可以像删除帖子一样删除术语元数据。 当我们使用delete_term_meta
函数时,如果需要,我们需要提供两个强制性参数,并提供第三个选项。
-
$term_id
– The ID of the term to work on.$term_id
–要处理的术语的ID。 -
$meta_key
– The meta key that will be removed from the term.$meta_key
–将从术语中删除的元**。 -
$meta_value
(optional) – Only delete the metadata if the value matches this value. Use this when you only want this data removed when it matches a set value.$meta_value
(可选)–仅在值与该值匹配时才删除元数据。 仅当您希望此数据与设置值匹配时才将其删除时,请使用此选项。
Once again let’s look at a scenario in which you might use this. Imagine your half way through a big project and you’ve already saved several pieces of meta data to each category term. You’ve found that some of this data you no longer need so you should probably clear it so that it doesn’t clutter up your database.
再次让我们看一下您可能会用到的场景。 想象一下您完成一个大型项目的过程,并且您已经为每个类别术语保存了几条元数据。 您已经发现不再需要其中的某些数据,因此您应该清除它,以免使数据库混乱。
//removed metadata we no longer need for each category term
function delete_old_meta_data_from_category(){
//get all category terms
$terms = get_terms('category', array('hide_empty' => false, 'fields' => 'ids'));
if($terms){
//list of allowed term keys
$allowed_term_keys = array('term_image_id', 'term_size');
//go through all category terms
foreach($terms as $term_id){
$term_meta = get_term_meta($term_id);
//go through all meta for each term
foreach($term_meta as $meta_key => $meta_value){
//if this meta key doesn't exist in our allowed term keys, delete it
if(!array_key_exists($meta_key, $allowed_term_keys)){
delete_term_meta($term_id, $meta_key);
}
}
}
}
}
add_action('init', 'delete_old_meta_data_from_category');
This function will go through and remove any additional metadata we didn’t specify in our $allowed_term_keys
variable, cutting down on wasted space in the database (useful for when we have dozens of metadata entries we no longer need).
此函数将删除所有未在$allowed_term_keys
变量中未指定的其他元数据,从而减少了数据库中的浪费空间(对于当我们不再需要数十个元数据条目时很有用)。
与WordPress 4.3及更低版本的向后兼容性 (Backwards Compatibility with WordPress 4.3 and Older)
If you were really keen on moving forward with these new meta functions but wanted to cover yourself against older versions, you could create some conditional functionality to ensure it all works.
如果您真的很想继续使用这些新的meta函数,但又想将自己覆盖旧版本,则可以创建一些条件功能来确保它们都能正常工作。
//add a piece of metadata for a term
function add_term_meta_compat($term_id, $term_key, $term_value){
if(function_exists('add_term_meta')){ //WP4.4+
add_term_meta($term_id, $term_key, $term_value, true);
}else{ //Pre WP4.4
//get term object and data
$term_object = get_term($term_id);
$term_taxonomy = $term_object->taxonomy;
//build final key to save (tax + termid + key)
$term_final_key = ($term_taxonomy . '_' . $term_id . '_' . $term_key);
//ensure key isn't longer than 64 characters (max limit)
$term_final_key = strlen($term_final_key > 64) ? substr($term_final_key, 0, 63) : $term_final_key;
//add our new option
add_option($term_final_key, $term_value);
}
}
We start by calling function_exists
to ensure that the new add_term_meta
function is defined. This will only be true for WordPress 4.4 and newer. If we have support we use the simple add_term_meta
function to assign metadata to our term.
我们首先调用function_exists
以确保定义了新的add_term_meta
函数。 这仅适用于WordPress 4.4及更高版本。 如果有支持,我们将使用简单的add_term_meta
函数将元数据分配给我们的术语。
If we don’t have support we grab the term object itself (by the passed in term ID) and from that we extract the $term_taxonomy
data and use it to build our final key value. Since we are saving into the options table we need to ensure the key is unique, we do this by adding the taxonomy name, the term ID and finally the term key into one variable. We must ensure the key isn’t greater than 64 characters long and if so trim it down. Once we’ve done all of this we can call our add_option
function to save our value.
如果没有支持,我们将获取术语对象本身(通过传入的术语ID),然后从中提取$term_taxonomy
数据并将其用于构建最终键值。 因为我们要保存到选项表中,所以我们需要确保键是唯一的,所以我们通过将分类法名称,术语ID和最后将术语关键字添加到一个变量中来实现。 我们必须确保**的长度不超过64个字符,如果是,则将其修剪掉。 一旦完成所有这些操作,就可以调用add_option
函数来保存我们的值。
As you can see, this gets a bit long, but you do get added flexibility to support older and newer WordPress versions.
如您所见,这有点长,但是您确实获得了更大的灵活性来支持旧的和较新的WordPress版本。
包装全部 (Wrapping It All Up)
Using these new meta functions should enable you to more easily extend your terms to provide unique functionality. For example, you might want to add a banner image to the top of your terms or provide metadata so you can conditionally display your terms differently (such as loading a new template file based on what term is being displayed).
使用这些新的元函数应该使您能够更轻松地扩展条款以提供独特的功能。 例如,您可能希望在标题的顶部添加标题图像或提供元数据,以便可以有条件地以不同方式显示您的术语(例如根据显示的术语加载新的模板文件)。
With the flexibility and ease of the new term meta functions you can start implementing this in your new projects today!
有了新功能元函数的灵活性和便捷性,您就可以立即在新项目中实现它!