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

Im looking for a way to add an alternating even/odd class directly to each image attachment when its outputted via my function below:

<?php
function nongallery_img_slide( $post_id = null ) {
    if ( $post_id == null ) return;
    $images = get_posts(
        array(
            'numberposts' => -1,
            'post_type' => 'attachment',
            'post_mime_type' => 'image',
            'post_parent' => $post_id,
            'orderby' => 'menu_order',
            'order' => 'ASC',
            //'exclude' => get_post_thumbnail_id( $post_id )
        )
    );
    if ( count( $images ) > 0 ) {
        foreach ( $images as $image ) {
            echo wp_get_attachment_image( $image->ID, 'photogallery-img' );
        }
    }
}
?>

Can this be done?
Thanks!

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

wp_get_attachment_image() has a fourth parameter for custom attributes. Use it:

if ( count( $images ) > 0 ) {
    $i = 0;
    foreach ( $images as $image ) {
        echo wp_get_attachment_image( 
            $image->ID, 
            'photogallery-img',
            FALSE,
            array (
                'class' => 'attachment-photogallery-img ' 
                . ( ( $i++ % 2 === 0 ) ? 'even' : 'odd' )
            )
        );
    }
}
share|improve this answer
    
Holy crap, I didnt even know it existed!..I will try this. Thanks for the quick response! Wow...so many possibilities now. Thanks so much. –  Mr.Brown Oct 5 '12 at 18:03
    
May I ask, is there a way to limit this array to only being applied to images when there is more than 1? -- that way, if I were to say only add one image to a post the "even/odd" classes would not be applied? Thanks! –  Mr.Brown Dec 5 '12 at 4:36
    
@Mr.Brown count( $images ) > 1. –  toscho Dec 5 '12 at 8:25
    
Hi @toscho, thanks for the response...changing the count to 1 seems to completely eliminate any images from showing up all together when there is ONLY 1 in the post now. I still want to be able to use the function to pull ALL attachments in, but rather apply "even/odd classes" to only images uploaded in "twos" (ie. pairs), if that makes any sense?...Thanks again for the help. –  Mr.Brown Dec 13 '12 at 21:15
add comment

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.