Hi EE forums,
I’m looking for a more elegant way to accomplish the following inside of a single-entry page:
Keep in mind that each channel entry is filed under multiple (parent-level) categories and there is no category segment to reference in the URL. I will eventually employ a plugin solution as to avoid using PHP inside the template, however, I’m looking to get some feedback on this approach first:
Code
<ul>
<?php
$i = 0;
// get the classes for the category
function get_category_classes($index, $channel_category, $indexClass = 'odd', $activeClass = 'selected')
{
$classes = array();
$output = '';
// is the iterator an odd number?
if ($index % 2 == 0) array_push($classes, $indexClass);
// does the channel category match any of the entry categories?
$entry_categories = explode(' ', '{categories}{category_name} {/categories}');
if (in_array($channel_category, $entry_categories)) array_push($classes, $activeClass);
// format the output (e.g. class="odd selected" or class="odd")
if ( ! empty($classes)) $output = ' class="'.trim(implode(' ', $classes)).'"';
return $output;
}
?>
{exp:channel:categories channel="blog" style="linear"}
<li<?= get_category_classes($i, '{category_name}') ?>>
<a href="http://{path=blog}">{category_name}</a>
</li>
<?php $i++ ?>
{/exp:channel:categories}
</ul>With respect to using an iterator to mark list items as “odd”: my first inclination was to use the {switch='odd|even'} tag. Sadly, this tag does not work correctly inside {exp:channel:categories} (e.g. it will return “odd” for every item). This is a known limitation, correct?
EE Info
Version: 2.4.0
Build: 20120123
Hey elative,
Thank you for your question.
This is an interesting question, but as it’s related to PHP programming, I am going to bump this over to Development and Programming where you will get some great feedback on how to make this work for you.
If there is anything support related I can do for you, please do let me know by opening a new thread.
Thanks again for your question.
Cheers,
Packet Tide owns and develops ExpressionEngine. © Packet Tide, All Rights Reserved.