ridgey28

WP Assign a class to each div in a foreach loop

Jun 19th, 2013
166
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php /* Assign a class to each div in a foreach loop for the following blog post:  
  2.     http://www.worldoweb.co.uk/2012/display-your-wordpress-recent-posts-on-a-static-page
  3.       */
  4.     $args = array( 'numberposts' => 3, 'post_status'=>"publish",'post_type'=>"post",'orderby'=>"post_date");
  5.    
  6.     $postslist = get_posts( $args );
  7.     $count = 0; // set up a post counter
  8.     $class = '';
  9.    
  10.     foreach ($postslist as $post) :  setup_postdata($post);
  11.         $count++;
  12.             switch ($count) {
  13.                 case 1:
  14.                     $class = ' class="one"';// change div class here and below to suit your needs
  15.                     break;
  16.                 case 2:
  17.                     $class = ' class="two"';
  18.                     break;
  19.                 case 3:
  20.                     $class = ' class="three"';
  21.                     break;
  22.                 default:
  23.                     $class= ' class="other_div"';//added default div as an example
  24.                     break;
  25.             }//end switch?>
  26.                                            
  27.     <div <?php echo $class ; ?>>
  28.         <strong><?php echo get_the_date(); ?></strong>
  29.         <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
  30.     </div>
  31.     <?php endforeach; ?>
RAW Paste Data