0

A specific API, returns an image in binary in the data.

If I need to save it to the server, I can easily do it by following the code.

$response = curl_exec($curl); // This is the API response
file_put_contents('example2.png', $response);

How can I add it to the WordPress media library?

3
  • 1
    The media library doesn't show files, it shows posts of type attachment, what you're asking about is called sideloading in the WordPress API. Just Putting images in the uploads folder on its own won't make them show up in the media library, and it's easier to give WP a file from a temporary folder that it can move into the preferred location by itself and generate the various image sizes
    – Tom J Nowell
    Commented Feb 6, 2023 at 16:31
  • @TomJNowellAs Thanks, As I understand, I need to give the URL of the image to download to media_sideload_image function. So here do I need to file_put_contents and then media_sideload_image or is there any way to pass to binary response to directly to media_sideload_image ?
    – Ranuka
    Commented Feb 6, 2023 at 18:27
  • if you want to use that function yes, but there are other and better functions such as media_handle_sideload, there is no reason to download a file here
    – Tom J Nowell
    Commented Feb 6, 2023 at 18:35

1 Answer 1

0

You should use media_handle_sideload. Write your file out to the filesystem then use media_handle_sideload to process it in the same way any other upload is processed. Be sure to cleanup afterwards.

See: https://developer.wordpress.org/reference/functions/media_handle_sideload/#comment-983 for an example

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.