Shopify’s Cycle lets you alternate between things within a loop. Here’s my example:
<div class="{% cycle 'first', 'second', 'third' %}">
{% include 'product-grid-item' %}
</div>
My question, is there anything like this for WordPress? I’d love to be able to cycle through some kind of setting – such as class names – as each item in my loop is printed.
Short answer, no.
But that is a pretty cool feature!
To so something similar in WordPress, you’d need to code some kind of iterator in PHP and have it do the logic for you. For example:
There’s nothing built into core but it’s easy to make something like this yourself. Here’s an example that would give posts classes post-count-1, post-count-2, post-count-3, post-count-1, ….2, ….3, …1, etc.:
If you wanted plain English classes, you’d need an
if
orswitch
statement to set$count
. This example also usespost_class
which gives you some other useful classes.ADDENDUM:
I should add that if you don’t need extensive browser support (:nth-child() CSS selector is really the right solution if you need the classes purely for styling. jQuery also supports this selector and you can use it to add the classes after page-load if you need better-than-the-CSS browser support.
Not exactly, but WordPress does have
body_class
andpost_class
, which by default will give you custom selectors, which can further be customized with any name or variable of your choosing.http://codex.wordpress.org/Function_Reference/body_class
http://codex.wordpress.org/Function_Reference/post_class
You are also able to use them as a filter, for example;
ps. Sorry I misunderstood the question, didn’t realize you wanted it exactly the same in terms of numerical classing.
This is one of my favorite helpers in Rails (which Shopify created a link to in its Liquid template language). I wrote a function similar to this for WordPress, enjoy: