node-wpapi icon indicating copy to clipboard operation
node-wpapi copied to clipboard

Adding media to post doesn't work

Open smartm0use opened this issue 5 years ago • 5 comments

Hello, I'm trying to create a post with an image. Here is my code:

const downloadFile = (async (url, path) => {
    const res = await fetch(url);
    const fileStream = fs.createWriteStream(path);
    await new Promise((resolve, reject) => {
        res.body.pipe(fileStream);
        res.body.on("error", (err) => {
            reject(err);
        });
        fileStream.on("finish", function() {
            resolve();
        });
    });
});

await downloadFile(itemUrl, './tempImage.jpg');

const responseUploadImage = await wp.media()
    .file('./tempImage.jpg')
    .create({
        title: 'My awesome image',
        alt_text: 'an image of something awesome',
        caption: 'This is the caption text',
        description: 'More explanatory information'
    });

const responsePostCreation = await wp.posts().create({
    title: 'Your Post Title',
    content: 'Your post content',
    // status: 'publish'
});

const response = await wp.media().id(responseUploadImage.id).update({
    post: responsePostCreation.id
});

console.log(response);

I get a new post and a new image in the media section on my Wordpress, but the post doesn't contains the image.

Here is the response of the last call:

{ id: 17,
  date: '2019-12-16T22:10:37',
  date_gmt: '2019-12-16T21:10:37',
  guid:
   { rendered:
      'http://www.mywebsite.com/wp-content/uploads/2019/12/tempImage-4.jpg',
     raw:
      'http://www.mywebsite.com/wp-content/uploads/2019/12/tempImage-4.jpg' },
  modified: '2019-12-16T22:10:38',
  modified_gmt: '2019-12-16T21:10:38',
  slug: 'my-awesome-image-5',
  status: 'inherit',
  type: 'attachment',
  link: 'http://www.mywebsite.com/?attachment_id=17',
  title: { raw: 'My awesome image', rendered: 'My awesome image' },
  author: 2,
  comment_status: 'open',
  ping_status: 'closed',
  template: '',
  meta: [],
  permalink_template: 'http://www.mywebsite.com/?attachment_id=17',
  generated_slug: 'my-awesome-image-5',
  description:
   { raw: 'More explanatory information',
     rendered:
      '<p class="attachment"><a href=\'http://www.mywebsite.com/wp-content/uploads/2019/12/tempImage-4.jpg\'><img width="300" height="300" src="http://www.mywebsite.com/wp-content/uploads/2019/12/tempImage-4-300x300.jpg" class="attachment-medium size-medium" alt="an image of something awesome" srcset="http://www.mywebsite.com/wp-content/uploads/2019/12/tempImage-4-300x300.jpg 300w, http://www.mywebsite.com/wp-content/uploads/2019/12/tempImage-4-150x150.jpg 150w, http://www.mywebsite.com/wp-content/uploads/2019/12/tempImage-4.jpg 355w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>\n<p>More explanatory information</p>\n' },
  caption:
   { raw: 'This is the caption text',
     rendered: '<p>This is the caption text</p>\n' },
  alt_text: 'an image of something awesome',
  media_type: 'image',
  mime_type: 'image/jpeg',
  media_details:
   { width: 355,
     height: 355,
     file: '2019/12/tempImage-4.jpg',
     sizes: { medium: [Object], thumbnail: [Object], full: [Object] },
     image_meta:
      { aperture: '0',
        credit: '',
        camera: '',
        caption: '',
        created_timestamp: '0',
        copyright: '',
        focal_length: '0',
        iso: '0',
        shutter_speed: '0',
        title: '',
        orientation: '0',
        keywords: [] } },
  post: 18,
  source_url:
   'http://www.mywebsite.com/wp-content/uploads/2019/12/tempImage-4.jpg',
  missing_image_sizes: [],
  _links:
   { self: [ [Object] ],
     collection: [ [Object] ],
     about: [ [Object] ],
     author: [ [Object] ],
     replies: [ [Object] ],
     'wp:action-unfiltered-html': [ [Object] ],
     'wp:action-assign-author': [ [Object] ],
     curies: [ [Object] ] } }

All seems to go fine. So, what's wrong with it? Are you sure the last call is adding media to the given post?

smartm0use avatar Dec 16 '19 19:12 smartm0use

According to this article I have tried another way:

let responsePostCreation = await wp.posts().create({
    title: 'This post has media, tags & categories!',
    content: 'Excellent and compelling demonstration'
});

let responseMedia = await wp.media().file('./tempImage.jpg').create({
    title: 'Amazing featured image',
    // This property associates our new media record with our new post:
    post: responsePostCreation.id
});

But even in this case, it creates a new post, it adds a new image in the media gallery but I have no image in the post. Why?

smartm0use avatar Dec 18 '19 20:12 smartm0use

The same thing happens to me, did you manage to solve it?

ghost avatar May 03 '20 22:05 ghost

Same problem here. Is somebody working on it? Or have somebody a solution/workaround?

daaanny90 avatar Sep 17 '20 12:09 daaanny90

Here is my working code:

// Preparing to download image from internet
let downloadFile = (async (url, path) => {
    let res = await fetch(url);
    let fileStream = fs.createWriteStream(path);
    await new Promise((resolve, reject) => {
        res.body.pipe(fileStream);
        res.body.on("error", (err) => {
            reject(err);
        });
        fileStream.on('finish', function() {
            resolve();
        });
    });
});

// Downloading image to local path
await downloadFile(myImageLink, './myImage.jpg');

// Uploading image and creating the item in the Wordpress media gallery
let responseMediaCreation = await wp.media().file("./myImage.jpg").create({
    title: 'My image'
});

// Creating post on your Wordpress website
await wp.posts().create({
    title: myTitle,
    featured_media: responseMediaCreation.id,
    content: `<h2>${myTitle}</h2><img src="${responseMediaCreation.source_url}" /><div>${myText}</div>`,
    status: 'publish'
});

Hope this helps.

smartm0use avatar Sep 18 '20 09:09 smartm0use

Great ! But then how do you delete the file that you downloaded on the server ?

philohelp avatar Apr 19 '21 21:04 philohelp