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 to add a comment box to WordPressHow to add a comment box to WordPressApr 20, 2025 pm 12:15 PM

Enable comments on your WordPress website to provide visitors with a platform to participate in discussions and share feedback. To do this, follow these steps: Enable Comments: In the dashboard, navigate to Settings > Discussions, and select the Allow Comments check box. Create a comment form: In the editor, click Add Block and search for the Comments block to add it to the content. Custom Comment Form: Customize comment blocks by setting titles, labels, placeholders, and button text. Save changes: Click Update to save the comment box and add it to the page or article.

How to copy sub-sites from wordpressHow to copy sub-sites from wordpressApr 20, 2025 pm 12:12 PM

How to copy WordPress subsites? Steps: Create a sub-site in the main site. Cloning the sub-site in the main site. Import the clone into the target location. Update the domain name (optional). Separate plugins and themes.

How to write a header of a wordpressHow to write a header of a wordpressApr 20, 2025 pm 12:09 PM

The steps to create a custom header in WordPress are as follows: Edit the theme file "header.php". Add your website name and description. Create a navigation menu. Add a search bar. Save changes and view your custom header.

How to display wordpress commentsHow to display wordpress commentsApr 20, 2025 pm 12:06 PM

Enable comments in WordPress website: 1. Log in to the admin panel, go to "Settings" - "Discussions", and check "Allow comments"; 2. Select a location to display comments; 3. Customize comments; 4. Manage comments, approve, reject or delete; 5. Use <?php comments_template(); ?> tags to display comments; 6. Enable nested comments; 7. Adjust comment shape; 8. Use plugins and verification codes to prevent spam comments; 9. Encourage users to use Gravatar avatar; 10. Create comments to refer to

How to upload source code for wordpressHow to upload source code for wordpressApr 20, 2025 pm 12:03 PM

You can install the FTP plug-in through WordPress, configure the FTP connection, and then upload the source code using the file manager. The steps include: installing the FTP plug-in, configuring the connection, browsing the upload location, uploading files, and checking that the upload is successful.

How to copy wordpress codeHow to copy wordpress codeApr 20, 2025 pm 12:00 PM

How to copy WordPress code? Copy from the admin interface: Log in to the WordPress website, navigate to the destination, select the code and press Ctrl C (Windows)/Command C (Mac) to copy the code. Copy from a file: Connect to the server using SSH or FTP, navigate to the theme or plug-in file, select the code and press Ctrl C (Windows)/Command C (Mac) to copy the code.

What to do if there is an error in wordpressWhat to do if there is an error in wordpressApr 20, 2025 am 11:57 AM

WordPress Error Resolution Guide: 500 Internal Server Error: Disable the plug-in or check the server error log. 404 Page not found: Check permalink and make sure the page link is correct. White Screen of Death: Increase the server PHP memory limit. Database connection error: Check the database server status and WordPress configuration. Other tips: enable debug mode, check error logs, and seek support. Prevent errors: regularly update WordPress, install only necessary plugins, regularly back up your website, and optimize website performance.

How to close comments with wordpressHow to close comments with wordpressApr 20, 2025 am 11:54 AM

How to turn off a comment in WordPress? Specific article or page: Uncheck Allow comments under Discussion in the editor. Whole website: Uncheck "Allow comments" in "Settings" -> "Discussion". Using plug-ins: Install plug-ins such as Disable Comments to disable comments. Edit the topic file: Remove the comment form by editing the comments.php file. Custom code: Use the add_filter() function to disable comments.

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 Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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