0

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!

1 Answer 1

1

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' )
            )
        );
    }
}
4
  • 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, 2012 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, 2012 at 4:36
  • @Mr.Brown count( $images ) > 1.
    – fuxia
    Dec 5, 2012 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, 2012 at 21:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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