automatically save custom post type title as a category

I wonder if there is a way to automatically create category from my custom post type titles.
For example – if I create post named ‘sport’, the function will create a category – ‘sport’ automatically.

Related posts

1 comment

  1. Hook into save_post, and check if the category already exists (to avoid double creation on post edit). If category doesn’t exist create it using wp_insert_term and assign to post using wp_set_object_terms

    add_action('save_post', 'add_title_as_category');
    
    function add_title_as_category( $postid ) {
      if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return;
      $post = get_post($postid);
      if ( $post->post_type == 'post') { // change 'post' to any cpt you want to target
        $term = get_term_by('slug', $post->post_name, 'category');
        if ( empty($term) ) {
          $add = wp_insert_term( $post->post_title, 'category', array('slug'=> $post->post_name) );
          if ( is_array($add) && isset($add['term_id']) ) {
            wp_set_object_terms($postid, $add['term_id'], 'category', true );
          }
        }
      }
    }
    

    If you want to set a custom taxonomy instead of the standard category replace 'category' with the custom taxonomy name everywhereit appear in code above.

Comments are closed.