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?

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)

| improve this answer | |
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.

| improve this answer | |
  • Hi Fred, sorry I meant auto URLs like "95032257420" instead of the URL title... – rey Sep 18 '14 at 10:17
  • 1
    I wrote a plugin that allows you to generate strings like that: github.com/sjelfull/Craft-Randomm – Fred Carlsen Sep 18 '14 at 23:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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