WordPress.org

Ready to get started?Download WordPress

Forums

Giving php generated divs different classes (3 posts)

  1. CrispySinger
    Member
    Posted 2 months ago #

    I'm wondering if its possible to generate a different class for each div that this php code generates. Theres a total of 5 divs that are going to be displayed after the script has ran.

    <?php $top_query = new WP_Query('cat=CaseStudies&showposts=5'); ?>
    <?php while($top_query->have_posts()) : $top_query->the_post(); ?>
    <?php
      echo '<div class="col-md-2 break project-img middle no-pad-mar">';
      echo '<div class="case caseimg">';
      the_post_thumbnail( 'thumbnail' );
    ?>
      <a href>/'">
      <span class="blk"><strong>Project Title</strong></span>       <span>Location</span></a>
    <?php
      echo '</div>';
      echo '</div>';
    ?>
    <?php $count1++; ?>
    <?php endwhile; ?>

    [Moderator Note: Please post code & markup between backticks or use the code button. Your posted code may now have been permanently damaged by the forum's parser.]

  2. stephencottontail
    Member
    Posted 2 months ago #

    What exactly are you trying to accomplish? WordPress provides a current_post object (in your case, it would be $top_query->current_post) that can be used. For example, <div class="foo-<?php echo $top_query->current_post; ?>"> would give you <div class="foo-0">, <div class="foo-1">, <div class="foo-2">, etc. You could also use current_post in a switch statement, if necessary.

  3. CrispySinger
    Member
    Posted 1 month ago #

    Sorry for the late reply. I got it working in the end by using a CSS "first-of-type" & "last-of-type" to get the five Divs to fit within the container properly.

    The issue was that the boxes wouldn't align with content above it and due to a client wanting the boxes to be spot on with that content I was required to edit it a bit. So I had to have the first and last divs flush with the side of the container and the rest aligned to suit. I'm using Roots to so that's why I needed to tweak it a bit to override some of the styles for generated column classes. Normally wouldn't be a problem but because I was using a for each loop to display the divs I was unsure as to how to style each div the way I wanted.

    Probably not the best fix but its working for now.

    Cheers for the help!

Reply

You must log in to post.

About this Topic