9

I have a custom section that uses routes like this:

/section/category/entry_url

In trying to program the search form results I realized that I need to explicitly define the entry URL format for the section so that the search results return the proper links to view the entries.

Currently I have /section/{category.slug}/{slug} but it is not working.

How would I set the entry URL format to include only the first category slug of the entry?

Thanks.

2 Answers 2

16

This got it working for me:

/section/{categoryFieldName.first.slug}/{slug}
4

As I understand it, you want the url for an entry to be /section/category-slug/entry-slug. This is a little tricky, because if the entry has no category defined, it won't have a url, which is why you can't just set the Entry URL Format.

If you really want to do this, you can do it using routes rather than the entry URL format. Uncheck the Entries in this section have their own URLs box, and create a route for section/[slug]/[slug] that points to your entry template.

On the entry template, you can figure out the category and entry slugs:

{% set categorySlug = craft.request.getSegment(2) %}
{% set entrySlug = craft.request.getSegment(3) %}

get the category:

{% set category = craft.category.slug(categorySlug) %}
{% if not category %}{% exit 404 %}{% endif %}

get the entry:

{% set entry = craft.entries.slug(entrySlug).relatedTo(category).first %}
{% if not entry %}{% exit 404 %}{% endif %}

Now you have the entry, proceed as usual.

When you need the entry url, that will be:

/section/{{ entry.category.first.slug }}/{{ entry.slug }}

I would write a macro for the entry url, and the macro can deal with the possibility of the entry having no category.

1
  • Right, I have all of that already. My question is related to URL returned in the search results. Under the section's settings config page where you check the "Entries in this section have their own URLs" box, for the "Entry URL Format" how do I specify that the category slug should be part of the URL format? Even if set the URL format to "section/{{ entry.category.first.slug }}/{slug}" the search results only returns "section//entry-slug" and drops the category slug from the URL. Jul 21, 2014 at 0:20

Your Answer

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

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