Insert Category Using Custom Code In WordPress

In this article I will show you how to Insert category using custom code in WordPress.

Everyone can insert category manually using WordPress admin panel. That task is so easy for any user.

But If you want to Insert any Category using your custom code.

Here I am going to mention some scenario when you need to create category dynamically.

For Example, If you are integrating some data through API and for some field you wanted to insert category then you will need to create category dynamically through the code.

Here is the reference code.

$slug = 'test-cat';
  $taxonomy_name = 'category';
  $parent = 0;
  $result = wp_insert_term($slug, $taxonomy_name,array(
    'description' => '',
    'parent'      => $parent,
    'slug'        => '',

as mentioned in above code you are able to insert category. Now you need to assign category with the relevant post.

For that you need to use, 

wp_set_post_terms( $post_id, [‘term_id’], $taxonomy_name ); // setting post category
Using this code you are able to assign the category to the post.
I hope this will Help. Kindly reach out to me through comments if you find any issue.

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories