2

How to auto-generate URLs in Craft? For example when we upload images on Tumblr, an URL to the post is created:

http://twotimeselliott.tumblr.com/post/95032257420

And an URL for the image is created:

http://31.media.tumblr.com/2142197f5273865770be44723c2a5df0/tumblr_nagyr9INCE1r6ky2bo1_500.jpg

How can we do that in Craft?

rey
  • 97
  • 6

2 Answers2

3

I’m not sure if those Tumblr URLs are just an incrementing ID (so each new post is +1 greater than the last one), or if it’s a randomly-generated string of numbers.

If you just want yours to be the entry ID, all you’d have to do is go into your section’s settings, and set the following:

  • Do entries in this section have their own URLs? [check]
  • Entry URL Format: post/{id}

If you want it to be random, that’s a little more difficult. You would need to create a custom text field that stores the random number, attach it to your section, and start entering random numbers into it when creating new entries (or you could write a custom field type that handles this for you). Then your Entry URL Format would get set to post/{customFieldHandle} instead of post/{id}.

As for the image URL, if you have an Assets field that’s responsible for storing the entry’s main image, you can set it to restrict uploads to a single directory, and give it a subfolder based on the entry’s ID/random number custom field handle. (See http://buildwithcraft.com/docs/assets-fields#restricting-uploads-to-a-single-folder)

Brandon Kelly
  • 34,307
  • 2
  • 71
  • 137
0

Entries have the url attribute, which you can access like so:

<a href="{{ entry.url }}">{{ entry.title }}</a>

See example in the docs

If you upload an image through Assets, you can get the url for the image by doing something like this:

<img src="{{ entry.imageHandle.first().getUrl() }}" alt="" />

Note that the getUrl takes an optional transform name, if you have added any transforms.

See more in the docs on craft.assets tag.

Fred Carlsen
  • 2,997
  • 13
  • 23