重磅付费教程免费读:WP如何添加前端编辑页来创建和编辑文章并实现用户登录才能编辑和权限控制

Published
2023-02-28
浏览次数 :  211

首先在前端创建表格来输入

<!-- content -->
            <form>

            <h2>前端投稿</h2>
            <input type="text" name="title" id="tougao-title" placeholder="文章标题">

            <h2>选择分类</h2>
            <select multiple name="tougao-category">
              <option value="reading">Reading</option>
              <option value="writing">Writing</option>
              <option value="traveling">Traveling</option>
              <option value="playing sports">Playing Sports</option>
              <option value="listening to music">Listening to Music</option>
            </select>

            <div class="input-container">
              <input id="tag-input" type="text" name="tougao-tag" placeholder="Type and hit enter to add a tag">
            </div>
            <div class="tags-container">
              <!-- Tags will be added here -->
            </div>

      <textarea name="content" id="tougao-content" cols="30" rows="10"></textarea>
      <input type="button" name="submit" id="tougao-submit" value="Submit">
    </form>

表格里面我添加了富文本编辑器,tinymce,如果大家也要用,只要在尾部添加一个js就可以了。

<script src="https://cdn.tiny.cloud/1/your-api-key/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>

富文本编辑器初始化:

tinymce.init({
        selector: '#tougao-content',
        height: 500,
        plugins: [
          'advlist autolink lists link image charmap print preview anchor',
          'searchreplace visualblocks code fullscreen',
          'insertdatetime media table paste code help wordcount'
        ],
        toolbar:
          'undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help',
        content_css: '//www.tiny.cloud/css/codepen.min.css'
      });

接下来我们来实现前端Input表格里面tag输入能像后台一样,按回车添加tag: 这段代码相对复杂,但是要一个一个进行分析, 就是一个按回车的动作,添加了两个函数而已:

 const tagInput = document.getElementById('tag-input');
const tagsContainer = document.querySelector('.tags-container');
let tags = [];

tagInput.addEventListener('keydown', function(event) {
  if (event.key === 'Enter') {
    const tagValue = tagInput.value.trim();
    if (tagValue !== '') {
      addTag(tagValue);
      tagInput.value = '';
      updateData();
    }
  }
  return tags;
});

function addTag(tagValue) {
  tags.push(tagValue);
  const tagElement = document.createElement('div');
  tagElement.classList.add('tag');
  tagElement.innerHTML = `
    <span class="tag-value">${tagValue}</span>
    <span class="tag-close">&times;</span>
  `;
  const tagClose = tagElement.querySelector('.tag-close');
  tagClose.addEventListener('click', function() {
    removeTag(tagValue, tagElement);
    updateData();
  });
  tagsContainer.appendChild(tagElement);
  
}

function removeTag(tagValue, tagElement) {
  const index = tags.indexOf(tagValue);
  if (index !== -1) {
    tags.splice(index, 1);
  }
  tagsContainer.removeChild(tagElement);
}

function updateData() {
  const tagInputValue = tagInput.value;
  const allTags = [...tags, tagInputValue];
  const tagString = allTags.join(', ');
  // Insert the tagString variable into your data as needed
  
}

实现了前端页面按回车添加tag功能之后,Tags变量里已经存储了所有变量。

表单提交和信息插入

我们通过wp的rest api来创建请求。

你在url后面输入/wp-json你就会看到该网站所有的api。

文章的断点链接是/wp-json/wp/v2/posts。

点按表单的提交按钮,先验证表单内容, :

jQuery("#tougao-submit").click(function(e) {   var title = jQuery("#tougao-title").val();
      if (tinymce.get("tougao-content") !== null) {
        var content = tinymce.get("tougao-content").getContent();
      }
      
        //check the value if is true return 
        if (title == '' || content == '') {

          swal({
            title:'the form is empty check again',
            icon:'error'
          });
          

        }   } else { }

如果表单内容通过,都不为空而且符合需要设置的规则, (规则可以通过Input的pattern设置,比方说可以设置手机号码验证、身份证号码验证等),

先定义凭证: 我这里用的是application password,用base 64 验证. 推荐用Nonce .

const password = "";
              const username = '';
                const credentials = `${username}:${password}`;
                const encodedCredentials = btoa(credentials);

然后发送ajax到user/me断点来验证当前用户是否有权限:

jQuery.ajax({
            url: '/wp-json/wp/v2/users/me',
            method: 'GET',
            beforeSend: function(xhr) {
              xhr.setRequestHeader('X-WP-Nonce', hastart.nonce_1);
            },

            success: function(data) {  //有权限执行  },
             error: function(err) {
                // The user is not logged in
                swal({
                  title:"You are not logged in",
                icon: "error",
              });
                console.log(err);
            }

再有权限的执行那里我们就发送post请求到posts的断点,附带authorization的验证,来进行文章的写入:

注意这里的url一定要是完整实际的url, 如果只是相对的/wp-json/wp/v2/posts, 可能会不行。

jQuery.ajax({

                  url:'你的url/wp-json/wp/v2/posts',
                  method:'POST',
                  
                  beforeSend: function(xhr)  {
                    xhr.setRequestHeader("Authorization",`Basic ${encodedCredentials}`);
                  },
                  data:{
                    title:title,
                    content:content,
                    tags:tags,
                    status:'publish',
                  },

                  success: function(res) {
                    console.log(tags);
                     swal({
                        title:"Success post",
                      icon: "success",
                    }).then(name=> {
                      if (name) {
                         location.reload();
                      }
                    });

                  },
                  error: function(err) {
                    console.log(err.responseText);
                  }

                });

如果要实现Tags内容的插入怎么搞,在rest api里,tags和category返回的都是id, 所以要实现全新插入,要多发一个请求到tags的断点: 下面是完整的代码:

// Set the post content and tags
const postContent = 'Your post content';
const tagSlugs = ['tag-1', 'tag-2', 'tag-3'];

// Get the tag IDs for the specified slugs
const tagIds = [];
$.when.apply($, tagSlugs.map(function(slug) {
  return $.ajax({
    url: 'https://your-wordpress-site.com/wp-json/wp/v2/tags',
    data: { slug: slug },
    dataType: 'json'
  }).done(function(response) {
    if (response.length > 0) {
      tagIds.push(response[0].id);
    } else {
      // Create a new tag with the specified slug
      $.ajax({
        url: 'https://your-wordpress-site.com/wp-json/wp/v2/tags',
        method: 'POST',
        beforeSend: function(xhr) {
          xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);
        },
        data: {
          name: slug,
          slug: slug
        },
        dataType: 'json'
      }).done(function(response) {
        tagIds.push(response.id);
      });
    }
  });
})).done(function() {
  // Create a new post with the specified tags
  $.ajax({
    url: 'https://your-wordpress-site.com/wp-json/wp/v2/posts',
    method: 'POST',
    beforeSend: function(xhr) {
      xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);
    },
    data: {
      title: 'Your post title',
      content: postContent,
      tags: tagIds
    },
    dataType: 'json'
  }).done(function(response) {
    console.log('Post created:', response);
  });
});

Top