Take the 2-minute tour ×
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 5 down vote accepted

This got it working for me:

/section/{categoryFieldName.first.slug}/{slug}
share|improve this answer

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.

share|improve this answer
    
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. –  pixelJitsu Jul 21 at 0:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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