星期三 , 22 1 月 2025

前端编辑器正确传递tags ajax结果到posts post

因为posts的rest api 的data 里面需要 data: tags: [167,168] 这种形式才能写入

// Retrieve the values of tags and categories from the input fields
        const tagslugs = $('#tg-tag').val().split(','); // Assuming tags are comma-separated
        const categories = $('#tg-category').val(); // Assuming only one category is selected
        if (Array.isArray(tagslugs) && tagslugs != '') {
    const tagPromises = tagslugs.map(slug => {
      return $.get(new_cc.restUrl + 'wp/v2/tags', { slug: slug })
        .then(res => {
          if (res.length > 0) {
            return res[0].id;
          } else {
            return $.ajax({
              url: new_cc.restUrl + 'wp/v2/tags',
              method: 'POST',
              beforeSend: (xhr) => {
                xhr.setRequestHeader('X-WP-Nonce', new_cc.nonce);
              },
              data: {
                name: slug,
                slug: slug
              }
            }).then(res => res.id)
              .catch(err => {
                console.log(err);
                return null;
              });
          }
        })
        .catch(err => {
          console.log(err);
          return null;
        });
    });

    Promise.all(tagPromises)
      .then(tagIds => {
        const validTagIds = tagIds.filter(id => id !== null);
        console.log('Tag IDs:', validTagIds); // Check if validTagIds contains the expected IDs

        // Proceed with creating the post using validTagIds and categories
        $.ajax({
          url: new_cc.restUrl + 'wp/v2/posts',
          type: 'POST',
          beforeSend: function(xhr) {
            xhr.setRequestHeader('X-WP-Nonce', new_cc.nonce);
          },
          data: {
            title: 'article with post title',
            content: 'moon is shine here is the new post',
            categories: categories,
            tags: validTagIds,
            status: 'publish'
          }
        })
          .done(res => {
            console.log(res);
            // Further actions after post creation success
          })
          .fail(err => {
            console.log(err.responseText);
            // Further actions on post creation failure
          });
      })
      .catch(err => {
        console.error('Error while retrieving/creating tag IDs:', err);
      });
        	

        } else {
        	console.log('tags input is empty');
        }

解释为什么.when.then方法不行

代码中的问题可能与$.wwhen.apply()方法中AJAX请求的异步性质有关。$.wwhen.apply()方法等待所有承诺都得到解析,然后再转到下一个.then()块。然而,代码的结构可能无法确保在随后的AJAX请求创建帖子之前,所有标签ID都被推送到标签ID数组中。

为了确保post请求仅在收集完所有标记ID后发送,您需要修改代码结构。一种方法是将Promise.all与从AJAX请求创建的Promise数组一起使用,以检索或创建标记。在所有与标签相关的承诺都得到解决后,您就可以继续进行后期创建了。

如果坚持用.when.then 版本

if (this.checkValidity()) {
  const formData = new FormData(this);

  const tagslugs = $('#tg-tag').val().split(','); // Assuming tags are comma-separated
  const categories = $('#tg-category').val(); // Assuming only one category is selected

  if (Array.isArray(tagslugs) && tagslugs.length > 0) {
    let tagPromises = tagslugs.map(slug => {
      return $.get(new_cc.restUrl + 'wp/v2/tags', { slug: slug })
        .then(res => {
          if (res.length > 0) {
            return res[0].id;
          } else {
            return $.ajax({
              url: new_cc.restUrl + 'wp/v2/tags',
              method: 'POST',
              beforeSend: (xhr) => {
                xhr.setRequestHeader('X-WP-Nonce', new_cc.nonce);
              },
              data: {
                name: slug,
                slug: slug
              }
            }).then(res => res.id)
              .fail(err => {
                console.log(err);
                return null;
              });
          }
        })
        .catch(err => {
          console.log(err);
          return null;
        });
    });

    $.when.apply($, tagPromises)
      .then(function() {
        let tagIds = Array.from(arguments).map(id => id).filter(id => id !== null);
        console.log('Tag IDs:', tagIds); // Check if tagIds contains the expected IDs

        // Proceed with creating the post using tagIds and categories
        $.ajax({
          url: new_cc.restUrl + 'wp/v2/posts',
          type: 'POST',
          beforeSend: function(xhr) {
            xhr.setRequestHeader('X-WP-Nonce', new_cc.nonce);
          },
          data: {
            title: 'article with post title',
            content: 'moon is shine here is the new post',
            categories: categories,
            tags: tagIds,
            status: 'publish'
          }
        })
          .done(res => {
            console.log(res);
            // Further actions after post creation success
          })
          .fail(err => {
            console.log(err.responseText);
            // Further actions on post creation failure
          });
      })
      .fail(function(err) {
        console.error('Error while retrieving/creating tag IDs:', err);
      });
  } else {
    console.log('Tags input is empty');
  }
} else {
  console.log('Form is not valid');
}

这种方法利用$.wwhen.apply()方法来等待多个AJAX请求的解析,并通过arguments对象收集它们的结果。然后,它过滤掉空值,并使用收集的tagId继续创建帖子。根据您的具体要求和错误处理需要进一步调整代码。