0
0
WordpressHow-ToBeginner · 4 min read

How to Add Category in WordPress: Step-by-Step Guide

To add a category in WordPress, go to the Posts menu in the admin dashboard and select Categories. Then, fill in the category name and click Add New Category to save it.
📐

Syntax

In WordPress, categories can be added via the admin dashboard or programmatically using PHP functions.

Admin Dashboard: Navigate to Posts > Categories, enter the category name, slug (optional), parent category (optional), and description (optional), then click Add New Category.

Programmatically: Use the wp_insert_term() function with parameters for the category name and taxonomy.

php
<?php
// Add a category programmatically
wp_insert_term(
  'New Category', // Category name
  'category',     // Taxonomy
  array(
    'description'=> 'A description for the new category',
    'slug' => 'new-category'
  )
);
?>
Output
Returns an array with 'term_id' and 'term_taxonomy_id' on success or a WP_Error object on failure.
💻

Example

This example shows how to add a category named "Travel" with a slug "travel" using PHP code in a theme's functions.php file or a custom plugin.

php
<?php
// Add 'Travel' category programmatically
$result = wp_insert_term(
  'Travel',
  'category',
  array(
    'description' => 'Posts related to travel experiences',
    'slug' => 'travel'
  )
);

if (is_wp_error($result)) {
  echo 'Error adding category: ' . $result->get_error_message();
} else {
  echo 'Category added successfully with ID: ' . $result['term_id'];
}
?>
Output
Category added successfully with ID: 123
⚠️

Common Pitfalls

  • Trying to add a category with a name that already exists will cause an error.
  • Not specifying the taxonomy as category when using wp_insert_term() will fail.
  • Forgetting to check for errors after calling wp_insert_term() can hide problems.
  • Adding categories via code without proper hooks may not run at the right time.
php
<?php
// Wrong way: missing taxonomy
wp_insert_term('News'); // This will fail

// Right way:
wp_insert_term('News', 'category');
?>
📊

Quick Reference

Here is a quick summary of how to add categories in WordPress:

MethodStepsNotes
Admin DashboardPosts > Categories > Enter name > Add New CategoryEasy, no code needed
PHP CodeUse wp_insert_term('Name', 'category', args)For automation or plugins
Check ErrorsUse is_wp_error() after wp_insert_term()Avoid silent failures
SlugOptional URL-friendly nameDefaults from category name

Key Takeaways

Add categories easily via WordPress admin under Posts > Categories.
Use wp_insert_term() in PHP to add categories programmatically.
Always specify 'category' as the taxonomy when adding categories in code.
Check for errors after adding categories programmatically to handle duplicates.
Category slugs are optional but help create clean URLs.