Jump to content
Sign in to follow this  
Jonathan Lahijani

How to add an image with non-standard filename and rename it via API

Recommended Posts

Let's say you want to add an image using the PW API from an outside service that doesn't provide a clean filename like my-cool-image.jpg (such as from dummyimage.com, urlbox.io, etc).

Doing it this way will add the image successfully, but the filename will be problematic and have an invalid extension (bad):

$p = $pages->get(1);
$p->your_single_image_field = "https://dummyimage.com/600x400/000/fff";
$p->save();

Instead, you need to rename the file right before save (good):

$p = $pages->get(1);
$p->your_single_image_field = "https://dummyimage.com/600x400/000/fff";
$p->your_single_image_field->first->rename("better.png"); // need 'first' here
$p->save();

 

  • Like 4

Share this post


Link to post
Share on other sites

Thanks for this Jonathan.

Since this is a tutorial, maybe new users would like to know, is there a way to programmatically rename the file to something related to the image, rather than renaming it to 'better.png' every time ? 🙂.

By the way, a

$p->save('your_single_image_field'); 

is more efficient since it will only save the field where changes have occurred. Just thought to point this out, in case the page has lots of fields, repeaters, etc. 😉

  • Like 3

Share this post


Link to post
Share on other sites
2 hours ago, kongondo said:

Since this is a tutorial, maybe new users would like to know, is there a way to programmatically rename the file to something related to the image, rather than renaming it to 'better.png' every time ? 🙂.

That would depend on the nature of what one needs.  But perhaps if you wanted to name it the name of the page (assuming it's an existing page) you could do:

$p->your_single_image_field->first->rename("{$p->name}.png"); // need 'first' here

 

  • Like 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...