Tiago
Tiago

Reputation: 653

wordpress programmatically add post tags

I'm trying to programmatically add post tags to a new post using PHP and JS. I have the code that sends using ajax the id's I want to add, PHP check them if exists, if not create them. Then it searches by name, and send back to Ajax the ID's.

My problem resides in adding all post tags to post, since only the last one adds itselfs to post.

success: function(data) {
    for(var i = 0; i < data.length; i++) {
        var obj = data[i];
        console.log(obj.term_id);
        wp.data.dispatch('core/editor').editPost({tags: [obj.term_id]})
    }
},

Console.log writes all post tags ID's that should be added. When using wp.data.dispatch('core/editor').editPost({tags: [obj.term_id]}) inside the for loop, it only adds the last ID to the post. In my specific case I have two ID's, one for each post tag (id 51 and 110) but it only adds the ID 110 to the post.

Isn't supposed to add both since it's inside a for loop?

Thanks

Upvotes: 0

Views: 746

Answers (1)

charlietfl
charlietfl

Reputation: 171679

Best guess without knowing anything about the wp.data api is you want to create the full array of values and only call editPost() once ... passing in the whole array.

You can use Array#map() to create the full array of terms from data.

Something like:

success: function(data) {

    var termsArray = data.map(function(el){ 
        return el.term_id; 
    });

    wp.data.dispatch('core/editor').editPost({tags: termsArray})

},

Upvotes: 2

Related Questions