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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.