0
0
Wordpressframework~5 mins

Taxonomy term management in Wordpress

Choose your learning style9 modes available
Introduction

Taxonomy term management helps organize content by grouping items with labels called terms. It makes finding and sorting content easier.

You want to group blog posts by topics like 'News' or 'Events'.
You need to add categories or tags to products in an online store.
You want users to filter content by custom labels like 'Difficulty Level'.
You want to create a menu of topics for visitors to browse content easily.
Syntax
Wordpress
<?php
// Get terms in a taxonomy
$terms = get_terms(array(
  'taxonomy' => 'category',
  'hide_empty' => false,
));

// Add a new term
wp_insert_term('New Term', 'category');

// Update a term
wp_update_term($term_id, 'category', array('name' => 'Updated Name'));

// Delete a term
wp_delete_term($term_id, 'category');
?>

get_terms() fetches terms from a taxonomy like categories or tags.

wp_insert_term(), wp_update_term(), and wp_delete_term() manage terms by adding, changing, or removing them.

Examples
This fetches all categories, even if no posts use them yet.
Wordpress
<?php
// Get all categories including empty ones
$categories = get_terms(array('taxonomy' => 'category', 'hide_empty' => false));
?>
This adds a new tag called 'Featured' to the post tags taxonomy.
Wordpress
<?php
// Add a new tag term
wp_insert_term('Featured', 'post_tag');
?>
This changes the name of the category with ID 12.
Wordpress
<?php
// Rename a category
wp_update_term(12, 'category', array('name' => 'Updated Category'));
?>
This deletes the tag with ID 34.
Wordpress
<?php
// Remove a tag
wp_delete_term(34, 'post_tag');
?>
Sample Program

This code lists all categories, then adds a new category called 'My New Category'. It shows success or error messages.

Wordpress
<?php
// Example: List all categories and add a new one

// Get all categories
$categories = get_terms(array('taxonomy' => 'category', 'hide_empty' => false));

// Print category names
foreach ($categories as $cat) {
  echo "Category: " . $cat->name . "\n";
}

// Add a new category
$new_term = wp_insert_term('My New Category', 'category');

if (is_wp_error($new_term)) {
  echo "Error adding category: " . $new_term->get_error_message() . "\n";
} else {
  echo "Added new category with ID: " . $new_term['term_id'] . "\n";
}
?>
OutputSuccess
Important Notes

Always check for errors when adding or updating terms using is_wp_error().

Term IDs are important to update or delete specific terms.

Use hide_empty => false to see all terms, even if no content uses them yet.

Summary

Taxonomy terms group content for easy organization and filtering.

Use WordPress functions like get_terms() and wp_insert_term() to manage terms.

Always handle errors and know term IDs when updating or deleting terms.