v2.5.2
Giriş yap

Wordpress REST API ile medya öğesi eklemek

emirhan
339 defa görüntülendi

Backend için Wordpress kullarak bir blog sitesi yapıyorum. İçerik düzenleyici için de <a href="https://editorjs.io/&quot;&gt;EditorJS&lt;/a&gt; kullanıyorum. Şuan EditorJS den aldığım bilgiyi WP REST API ile kaydediyor, kaydettiğim gönderileri düzenleyebiliyorum.
İstediğim şey ise görsel eklemek. EditorJS'in <a href="https://github.com/editor-js/image&quot;&gt;Image Block</a> adlı bir bloğu var.
Block ile seçtiğim görsel bana böyle bir obje döndürüyor. <b>Bu objeyi nasıl WP REST API ile kaydedebilir ve gönderilere ekleyebilirim?</b>

File { 
   name: "Gauge.png",
   lastModified: 1641031649209,
   webkitRelativePath: "",
   size: 7534,
   type: "image/png"
}

Bu EditorJS'in config dosyası.

const tools = {
  header: {
    class: Header,
    inlineToolbar: ["link"],
  },
  list: {
    class: List,
    inlineToolbar: true,
  },
  checklist: {
    class: Checklist,
    inlineToolbar: true,
  },
  embed: {
    class: Embed,
    inlineToolbar: true,
  },
  markertool: {
    class: MarkerTool,
    inlineToolbar: true,
  },
  image: {
    class: ImageTool,
    config: {
      additionalRequestHeaders: {
        "X-WP-NONCE" : nonceData.nonce,
      },
      uploader: {
        uploadByFile(file){
          let mainData = {
            "id"    : 'pkImg-' + file.lastModified,
            "date"  : file.lastModified,
            "body"  : file,
          }
          console.log(mainData);
          let imageUploader = new XMLHttpRequest();
          imageUploader.open("POST", homeUrl + '/wp-json/wp/v2/media/');
          imageUploader.setRequestHeader("X-WP-NONCE", nonceData.nonce);
          imageUploader.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
          return imageUploader.upload.then(() => {
            return {
              success: 1,
              file: {
                // url: 'https://exmaple.com/images/image.jpg',
                // any other image data you want to store, such as width, height, color, extension, etc
              }
            };
          });
        }
      }
    }
  },
};

const editor = new EditorJS({
  /**
   * Id of Element that should contain the Editor
   */

  holder: "editorjs",

  /**
   * Available Tools list.
   * Pass Tool's class or Settings object for each Tool you want to use
   */

  tools,
});

editor.isReady
  .then(() => {
    let editorTop = $("#editorTop");
    let editorBottom = $("#editorBottom");
    let titleInputAttrs = {
      id: "postTitle",
      name: "postTitle",
      placeholder: "Başlık",
      type: "text",
    };
    let excerptInputAttrs = {
      id: "postExcerpt",
      name: "postExcerpt",
      placeholder: "Özet",
      type: "textarea",
    };
    let tagInputAttrs = {
      id: "postTags",
      name: "postTags",
      placeholder: "Etiketler",
      type: "text",
    };
    $("<input>").attr(titleInputAttrs).appendTo(editorTop);
    $("<textarea>").attr(excerptInputAttrs).appendTo(editorBottom);
    $("<input>").attr(tagInputAttrs).appendTo(editorBottom);
    console.log("Editor.js is ready to work!");
    /** Do anything you need after editor initialization */
  })
  .catch((reason) => {
    console.log(`Editor.js initialization failed because of ${reason}`);
  });

$("#pkSendPost").on("click", function () {
  editor
    .save()
    .then((outputData) => {
      sendPostToDB(outputData, 'pending');
    })
    .catch((error) => {
      console.log("Saving failed: ", error);
    });
});

$("#pkSavePost").on("click", function () {
  editor
    .save()
    .then((outputData) => {
      sendPostToDB(outputData, 'draft');
    })
    .catch((error) => {
      console.log("Saving failed: ", error);
    });
});

Bu editorFunctions.js dosyam.

function convertParagraph(elType, elData){
    elDataText = elData.text;
    return '<p>' + elDataText + '</p>';
  }
  
  function convertHeader(elType, elData) {
    elDataText = elData.text;
    elDataLevel = elData.level;
    return '<h' + elDataLevel + '>' + elDataText + '</h' + elDataLevel + '>'; 
  }
  
  function convertChecklist(elType, elData) {
    elItems = elData.items;
    dummy_string = '';
    for (i=0; i < elItems.length; i++) { 
        elItem = elItems[i];
        elItemText = elItem.text;
        isChecked = elItem.checked ? 'checked' : '';
        dummy_string = dummy_string.concat('<label><input type="checkbox" ' + isChecked + '>' + elItemText + '</label>');
    }
    return dummy_string;
  }
  
  function convertEmbed(elType, elData) {
    let elId = el['id'];
    let elSource = elData['embed'];
    let elHeight = elData['height'];
    let elWidth = elData['width'];
    let elCaption = elData['caption'];
    return '<iframe id="' + elId + '" style="width: 100%;" src="' + elSource + '" height="' + elHeight + '"></iframe><style> #'+ elId +'::after {content: "'+ elCaption +'"} </style>';
  }
  
  function convertList(elType, elData) {
    let listStyle = elData['style'];
    let elItems = elData['items'];
    let dummy_string = '';
    if (listStyle == 'ordered') { var correntStyle =  'ol';} else { var correntStyle =  'ul'; };
    for (i=0; i < elItems.length; i++) { 
        elText = elItems[i];
        dummy_string = dummy_string.concat('<li>'+ elText +'</li>');
    }
    return '<' + correntStyle +'>' + dummy_string + '</'+ correntStyle +'>';
  }
  
  function type_to_el(el) {
  
    let elType = el['type'];
    let elData = el['data'];
  
    if (elType == 'paragraph') {
      return convertParagraph(elType, elData);
    }
    if (elType == 'header') {
      return convertHeader(elType, elData);
    }
    if (elType == 'checklist') {
      return convertChecklist(elType, elData);
    }
    if (elType == 'embed') {
      return convertEmbed(elType, elData);
    }
    if (elType == 'list') {
      return convertList(elType, elData);
    }
  }
  
  function sendPostToDB(outputData, status = 'draft', post_id = '') {
    let postTitle = $("#postTitle").val();
    let postExcerpt = $("#postExcerpt").val();
    let postTags = $("#postTags").val();
  
    var blockArray = outputData.blocks;
    
    let allContent = '';
  
    for (let i=0; i < blockArray.length; i++) {
      let el = blockArray[i];
      allContent = allContent.concat(type_to_el(el));
    }
  
    outputData = JSON.stringify(outputData)

    if (post_id == '') {
      let mainData = {
        "title"   : postTitle,
        "content" : allContent,
        "excerpt" : postExcerpt,
        // "tags"    : postTags,
        "status"  : status, 
        "meta"    : {
          "rawData" : outputData,
        }
      }
      let postSender = new XMLHttpRequest();
    
      postSender.open("POST", homeUrl + '/wp-json/wp/v2/posts');
    
      postSender.setRequestHeader("X-WP-NONCE", nonceData.nonce);
      postSender.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
      postSender.send(JSON.stringify(mainData));
      postSender.onreadystatechange = function() {
        if (postSender.readyState == 4) {
          if (postSender.status == 201) {
            // window.location.replace(homeUrl + '/yazilarim');
          }
          else {
            console.log('HATA');
          }
        }
      }
    } else {
      let mainData = {
        "id"      : post_id,
        "title"   : postTitle,
        "content" : allContent,
        "excerpt" : postExcerpt,
        // "tags"    : postTags,
        "status"  : status, 
        "meta"    : {
          "rawData" : outputData,
        }
      }
      let postSender = new XMLHttpRequest();
    
      postSender.open("POST", homeUrl + '/wp-json/wp/v2/posts/' + post_id);
    
      postSender.setRequestHeader("X-WP-NONCE", nonceData.nonce);
      postSender.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
      postSender.send(JSON.stringify(mainData));
      postSender.onreadystatechange = function() {
        if (postSender.readyState == 4) {
          if (postSender.status == 201) {
            // window.location.replace(homeUrl + '/yazilarim');
          }
        }
      }
    }
  }
Cevap yaz
Cevaplar (0)
Henüz kimse cevap yazmadı. İlk cevap yazan sen ol!