0

Using node. I want to upload some images to wordpress using the wordpress api. I tested and it works with png. Is this not possible with webp or maybe my code is wrong? I tried before with the UI and it works with webp.

This is the function

export async function testAddingMedia(league, teamAbbr1, teamAbbr2) {


  /* 
  IMPORTANT PART OF generateFeaturedMedia
  return await background
      .composite([
        { "input": team0LogoPath, "top": Math.round((metaBackground.height / 2) - (353)), "left": Math.round((metaBackground.width / 2) - 780) },
        {
          "input": team1LogoPath, "top":   Math.round((metaBackground.height / 2) - 
        (353)), "left":  Math.round((metaBackground.width / 2) + 195),
        },
      ])
      .webp()
      .toBuffer(); */
  const imageBuffer = await generateFeaturedMedia(
    teamAbbr1, // this is used to find some images and join in a new img
    teamAbbr2,
    league
  );
  
  const filename = "someName"
  const response = await fetch(apiMediaUrl, {
    "method":  'POST',
    "headers": {
      'Content-Disposition': `attachment; filename="${filename}"`,
      'Authorization':       `Basic ${token}`, // this is defined outside
      'Content-Type':        'image/webp',
    },
    "body": imageBuffer,
  });
  console.log("🚀 ~ testAddingMedia ~ response:", response)
}
testAddingMedia("NBA", "DAL", "UTA")

This is the answer

Response {

  status: 406,

  statusText: 'Not Acceptable',

  headers: Headers {

    date: 'Mon, 18 Nov 2024 20:20:34 GMT',

    'content-type': 'text/html; charset=iso-8859-1',

    'transfer-encoding': 'chunked',

    connection: 'keep-alive',

    'cf-cache-status': 'DYNAMIC',

    'set-cookie': '__cf_bm=jasjsdhh23894897hdgdgGSJGDjkdsjg-1731961234-1.0.1.1-L4exAiRCAXkg1.3WzbdExPCy810GjTFkjsdfjkdhFIFiudfhiuhSh_f3JfH155jCyVcbguU13_g; path=/; expires=Mon, 18-Nov-24 20:50:34 GMT; domain=.blog.ai; HttpOnly; Secure; SameSite=None, _cfuvid=Hsdhjasgdjg8734AVzjYTWJKYwaC...6ghUAhc-727645653529-0.0.1.1-604800000; path=/; domain=.blog.ai; HttpOnly; Secure; SameSite=None',

    server: 'cloudflare',

    'cf-ray': '8e4aa234987234-MIA'

  },

  body: ReadableStream { locked: false, state: 'readable', supportsBYOB: true },

  bodyUsed: false,

  ok: false,

  redirected: false,

  type: 'basic',

  url: 'https://blog.ai/wp-json/wp/v2/media'

}

Could you help he to find a way to upload the webp img to wordpress with the wordpress api

1 Answer 1

1

By default wordpress only allows certain file types for images (and still not webp or svg, among others). Hence the error 406 (Not acceptable).

To add support directly to wordpress (without a plugin), simply add these few lines to the functions.php of the theme you're using:

//Allow upload of image files in webp format.
function webp_upload_mimes($existing_mimes) {
    $existing_mimes['webp'] = 'image/webp';
    return $existing_mimes;
}
add_filter('mime_types', 'webp_upload_mimes');

//Declare image files in webp format as displayable objects (to display them in the media manager, for example).
function webp_is_displayable($result, $path) {
    if ($result === false) {
        $displayable_image_types = array( IMAGETYPE_WEBP );
        $info = @getimagesize( $path );

        if (empty($info)) {
            $result = false;
        } elseif (!in_array($info[2], $displayable_image_types)) {
            $result = false;
        } else {
            $result = true;
        }
    }

    return $result;
}
add_filter('file_is_displayable_image', 'webp_is_displayable', 10, 2);

These functions allow you to add images in webp format and display them in the media manager. Who can do more can do less. And it should work for the api too :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.