search
HomeCMS TutorialWordPressIntroduction to WordPress Term Meta and WP_Term

Introduction to WordPress Term Meta and WP_Term

Key Takeaways

  • Since WordPress 4.4, terms are now objects, making it easier to add, remove, and update metadata. Prior to this, saving metadata for taxonomies was a complex process that required saving term metadata as a field inside the wp_options table.
  • To work with term meta, the add_term_meta, update_term_meta, and delete_term_meta functions are used. These functions, combined with new UI elements, allow for the saving and updating of new metadata for terms.
  • Term metadata can be used to extend terms, providing unique functionality. Examples include adding a banner image to the top of terms or providing metadata to conditionally display terms differently, such as loading a new template file based on the term being displayed.
  • The WP_Term class in WordPress is an object-oriented representation of a term. It provides methods for retrieving and manipulating term data, including Term Meta. This class can be used to work with Term Meta by creating an instance of the class for a specific term, and then using the methods provided by the class to retrieve, add, update, or delete the term’s meta data.

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!).

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.

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.

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.

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).

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.

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.

Adding Term Meta

Adding metadata for a term involves the add_term_meta function. You need to specify three parameters with an optional fourth.

  • $term_id – ID of the term you want to save this metadata to
  • $meta_key – Key name of the metadata. This is how you will reference the data
  • $meta_value – The data itself (remember to sanitize)
  • $unique (optional) – If the metadata key should be unique. By default this is set to false and means that if another key has the same name the function it will override it. Set this to true to ensure uniqueness.

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).

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 = 1 && $term_count 
<h3 id="Reading-Term-Meta">Reading Term Meta</h3>
<p>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.</p>
  • $term_id – The ID of the term to fetch metadata from
  • $key (optional) – A single specified key you want to return. If not specified then all metadata is returned.
  • $single (optional) – If a single value will be returned or a key or value pair. Defaults to a single value.

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.

//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="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173958391434515.jpg?x-oss-process=image/resize,p_40" class="lazy" . title="' . $term->name . ' image" alt="Introduction to WordPress Term Meta and WP_Term" >';
        }  
    }
}

Now inside our category.php or other child theme template file, we can modify the functionality where our term data is displayed.

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.

//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:

Introduction to WordPress Term Meta and WP_Term

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.

  • $term_id – The ID of the term to work on.
  • $meta_key – The meta key that will be removed from the term.
  • $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.

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.

//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');

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).

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.

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 = 1 && $term_count 
<p>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.</p>
<p>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.</p>
<p>As you can see, this gets a bit long, but you do get added flexibility to support older and newer WordPress versions.</p>
<h2 id="Wrapping-It-All-Up">Wrapping It All Up</h2>
<p>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).</p>
<p>With the flexibility and ease of the new term meta functions you can start implementing this in your new projects today!</p><h2 id="Frequently-Asked-Questions-FAQs-about-WordPress-Term-Meta">Frequently Asked Questions (FAQs) about WordPress Term Meta</h2>



<h3 id="What-is-WordPress-Term-Meta">What is WordPress Term Meta?</h3> <p>WordPress Term Meta is a feature that allows you to store custom metadata for terms in your WordPress site. This metadata can be anything from additional descriptions, images, colors, or any other information you want to associate with a term. It’s a powerful tool that can enhance the functionality and user experience of your website.</p>  <h3 id="How-do-I-add-Term-Meta-in-WordPress">How do I add Term Meta in WordPress?</h3> <p>To add Term Meta in WordPress, you can use the add_term_meta() function. This function takes three required parameters: the term ID, the meta key (the name of the meta field), and the meta value. Optionally, you can also specify whether the meta key should be unique.</p>  <h3 id="How-can-I-retrieve-Term-Meta-data-in-WordPress">How can I retrieve Term Meta data in WordPress?</h3> <p>You can retrieve Term Meta data in WordPress using the get_term_meta() function. This function requires the term ID and the key of the meta field you want to retrieve. It returns the value of the meta field for the specified term.</p>  <h3 id="Can-I-update-Term-Meta-in-WordPress">Can I update Term Meta in WordPress?</h3> <p>Yes, you can update Term Meta in WordPress using the update_term_meta() function. This function requires the term ID, the meta key, and the new meta value. If the meta key does not exist for the term, it will be added.</p>  <h3 id="How-can-I-delete-Term-Meta-in-WordPress">How can I delete Term Meta in WordPress?</h3> <p>You can delete Term Meta in WordPress using the delete_term_meta() function. This function requires the term ID and the meta key. It deletes the specified meta field for the given term.</p>  <h3 id="What-is-the-WP-Term-class-in-WordPress">What is the WP_Term class in WordPress?</h3> <p>The WP_Term class in WordPress is an object-oriented representation of a term. It provides methods for retrieving and manipulating term data, including Term Meta.</p>  <h3 id="How-can-I-use-the-WP-Term-class-to-work-with-Term-Meta">How can I use the WP_Term class to work with Term Meta?</h3> <p>You can use the WP_Term class to work with Term Meta by creating an instance of the class for a specific term, and then using the methods provided by the class to retrieve, add, update, or delete the term’s meta data.</p>  <h3 id="What-are-some-practical-uses-of-Term-Meta-in-WordPress">What are some practical uses of Term Meta in WordPress?</h3> <p>Term Meta in WordPress can be used for a variety of purposes, such as adding additional information to categories or tags, creating custom fields for terms, enhancing search functionality, and more.</p>  <h3 id="Can-I-use-Term-Meta-with-custom-taxonomies-in-WordPress">Can I use Term Meta with custom taxonomies in WordPress?</h3> <p>Yes, you can use Term Meta with custom taxonomies in WordPress. The Term Meta functions work with any taxonomy, including custom ones.</p>  <h3 id="Are-there-any-plugins-that-can-help-me-manage-Term-Meta-in-WordPress">Are there any plugins that can help me manage Term Meta in WordPress?</h3> <p>Yes, there are several plugins available that can help you manage Term Meta in WordPress. These plugins provide user-friendly interfaces for adding, updating, and deleting Term Meta, making it easier for those who are not comfortable with coding.</p>

The above is the detailed content of Introduction to WordPress Term Meta and WP_Term. 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
How does WordPress's plugin ecosystem enhance its CMS capabilities?How does WordPress's plugin ecosystem enhance its CMS capabilities?May 14, 2025 am 12:20 AM

WordPresspluginssignificantlyenhanceitsCMScapabilitiesbyofferingcustomizationandfunctionality.1)Over50,000pluginsallowuserstotailortheirsiteforSEO,e-commerce,andsecurity.2)Pluginscanextendcorefeatures,likeaddingcustomposttypes.3)However,theycancausec

Is WordPress suitable for e-commerce?Is WordPress suitable for e-commerce?May 13, 2025 am 12:05 AM

Yes, WordPress is very suitable for e-commerce. 1) With the WooCommerce plugin, WordPress can quickly become a fully functional online store. 2) Pay attention to performance optimization and security, and regular updates and use of caches and security plug-ins are the key. 3) WordPress provides a wealth of customization options to improve user experience and significantly optimize SEO.

How to add your WordPress site in Yandex Webmaster ToolsHow to add your WordPress site in Yandex Webmaster ToolsMay 12, 2025 pm 09:06 PM

Do you want to connect your website to Yandex Webmaster Tools? Webmaster tools such as Google Search Console, Bing and Yandex can help you optimize your website, monitor traffic, manage robots.txt, check for website errors, and more. In this article, we will share how to add your WordPress website to the Yandex Webmaster Tool to monitor your search engine traffic. What is Yandex? Yandex is a popular search engine based in Russia, similar to Google and Bing. You can excel in Yandex

How to fix HTTP image upload errors in WordPress (simple)How to fix HTTP image upload errors in WordPress (simple)May 12, 2025 pm 09:03 PM

Do you need to fix HTTP image upload errors in WordPress? This error can be particularly frustrating when you create content in WordPress. This usually happens when you upload images or other files to your CMS using the built-in WordPress media library. In this article, we will show you how to easily fix HTTP image upload errors in WordPress. What is the reason for HTTP errors during WordPress media uploading? When you try to upload files to Wo using WordPress media uploader

How to fix the issue where adding media buttons don't work in WordPressHow to fix the issue where adding media buttons don't work in WordPressMay 12, 2025 pm 09:00 PM

Recently, one of our readers reported that the Add Media button on their WordPress site suddenly stopped working. This classic editor problem does not show any errors or warnings, which makes the user unaware why their "Add Media" button does not work. In this article, we will show you how to easily fix the Add Media button in WordPress that doesn't work. What causes WordPress "Add Media" button to stop working? If you are still using the old classic WordPress editor, the Add Media button allows you to insert images, videos, and more into your blog post.

How to set, get and delete WordPress cookies (like a professional)How to set, get and delete WordPress cookies (like a professional)May 12, 2025 pm 08:57 PM

Do you want to know how to use cookies on your WordPress website? Cookies are useful tools for storing temporary information in users’ browsers. You can use this information to enhance the user experience through personalization and behavioral targeting. In this ultimate guide, we will show you how to set, get, and delete WordPresscookies like a professional. Note: This is an advanced tutorial. It requires you to be proficient in HTML, CSS, WordPress websites and PHP. What are cookies? Cookies are created and stored when users visit websites.

How to Fix WordPress 429 Too Many Request ErrorsHow to Fix WordPress 429 Too Many Request ErrorsMay 12, 2025 pm 08:54 PM

Do you see the "429 too many requests" error on your WordPress website? This error message means that the user is sending too many HTTP requests to the server of your website. This error can be very frustrating because it is difficult to find out what causes the error. In this article, we will show you how to easily fix the "WordPress429TooManyRequests" error. What causes too many requests for WordPress429? The most common cause of the "429TooManyRequests" error is that the user, bot, or script attempts to go to the website

How scalable is WordPress as a CMS for large websites?How scalable is WordPress as a CMS for large websites?May 12, 2025 am 12:08 AM

WordPresscanhandlelargewebsiteswithcarefulplanningandoptimization.1)Usecachingtoreduceserverload.2)Optimizeyourdatabaseregularly.3)ImplementaCDNtodistributecontent.4)Vetpluginsandthemestoavoidconflicts.5)ConsidermanagedWordPresshostingforenhancedperf

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor