简体   繁体   English

wordpress以编程方式添加帖子标签

[英]wordpress programmatically add post tags

I'm trying to programmatically add post tags to a new post using PHP and JS. 我试图使用PHP和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. 我有使用ajax发送要添加的ID的代码,PHP检查它们是否存在,如果不创建它们。 Then it searches by name, and send back to Ajax the ID's. 然后它按名称搜索,并将ID发送回Ajax。

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. Console.log写入所有应添加的帖子标签ID。 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. 在for循环内使用wp.data.dispatch('core/editor').editPost({tags: [obj.term_id]}) ,它只会将最后一个ID添加到帖子中。 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. 在我的特定情况下,我有两个ID,每个帖子标签一个ID(ID 51和110),但它仅将ID 110添加到帖子中。

Isn't supposed to add both since it's inside a for loop? 因为它在for循环中,所以不应该同时添加两者吗?

Thanks 谢谢

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. wp.data api的情况下,最好的猜测是您要创建值的完整数组,并且只调用一次editPost() ...传入整个数组。

You can use Array#map() to create the full array of terms from data . 您可以使用Array#map()data创建完整的术语数组。

Something like: 就像是:

success: function(data) {

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

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

},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM