Inserting post terms into DB separately

I am trying to add tags to my videos as terms and the problem is if i have more tags for one video they are stored in one variable and passed to the DB as a group, what i need to have is that every tag gets inserted to the db separately

Right now its like this:
Example :

Read More
$tags = #tag1 #tag2 #tag3
wp_insert_term( $tags, 'post_tag'); 

In the db it looks like

term_id           name              slug
   1        #tag1 #tag2 #tag3  tag1-tag2-tag3

and I would need it to be like this

term_id           name              slug
   1              #tag1             tag1
   2              #tag2             tag2
   3              #tag3             tag3

Related posts

Leave a Reply

2 comments

  1. WordPress doesn’t know what’s your intention, so

    $tags = '#tag1 #tag2 #tag3'
    

    is actually one variable. So, say it different, try the snippet below

    $tags = array('#tag1', '#tag2', '#tag3', '#tag4', '#tag5');
    foreach($tags as $tag){
        wp_insert_term(trim($tag), 'post_tag'); // just in case, use trim() for cleaning
    }
    

    Demo

    If you’d like to use explode(), be sure to clean each value using trim(); or better said be sure you don’t have an empty string.