How to Programmatically Create a Category in WordPress

By default, WordPress comes with a built in interface which allows you to add new categories to your website or blog. However, you can do the same thing using code. To do this, we are going to use wp_insert_term() function.

See Also : Programmatically Sign-on a WordPress User

To programmatically create a category, put the following code in your functions.php file.

//Programmatically Create Category in WordPress
function sample_insert_category() {
	if(!term_exists('sample-category')) {
		wp_insert_term(
			'Sample Category',
			'category',
			array(
			  'description'	=> 'This is an sample category.',
			  'slug' 		=> 'sample-category'
			)
		);
	}
}
add_action( 'after_setup_theme', 'sample_insert_category' );

As you can see, we are using if statement to determine if the category we want to create already exists, if not then it will create that category.

How to Programmatically Create Category in WordPress

How to Programmatically Create Category in WordPress

2 Comments

  1. Ah – this is a great idea if a custom built theme depends on particular categories existing! So assuming the user doesn’t randomly delete it however, the category will be present once the theme is activated right?

    Reply
    • Hey Rachel, sorry for the late reply.

      Yes. You are right. This snippet is very useful when we are building a custom theme that depends on a particular category.

      In this snippet, we have hooked our function with after_setup_theme action which is called during each page load, after the theme is initialized. So, after each page load, it will make sure if the required category is present, if not it will create that category.

      Reply

Leave a Comment.