[resolved] CSS class name based on incremental PHP name loop (4 posts)

  1. KhalidQ
    Posted 3 years ago #


    I'm trying to create a parallax page similar to https://www.spotify.com/uk/ setup, and have each post from a specific category come up, followed by a parallax scrolling image background under it.

    So I've added the background image code to be inserted automatically as each post is pulled, I know how many posts will be on the homepage, I just want to give the client the freedom to edit the content of them, so having too many isn't going to be an issue, but, I need to have an automatically generated class name based on a loop, so I can add the background-image using CSS to it, such as background1, background 2, background 3, etc..

    This is my code currently

    <?php query_posts('cat=2');?>
    	<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    	<div class="postWrap">
    		<div class="postContainer">
    				<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    		<?php the_content(); ?> 
    	<section class="[LOOP HELP HERE]" data-speed="4" data-type="background">
          <h2>Image goes here</h2>
    	<?php endwhile; else: endif; ?>

    Can someone help patch me up with the PHP side of this?


  2. bcworkz
    Posted 3 years ago #

    Edit the following two lines as shown:

    <?php query_posts('cat=2'); $ct = 0; ?>
    ...other code...
    <?php the_content(); $ct++; ?>

    and replace [LOOP HELP HERE] with <?php echo "background$ct"; ?>

  3. Mark / t31os

    Posted 3 years ago #

    Outside the loop(ie. anywhere before the while loop).

    $your_counter = 0;

    Then immediately after the while ( have_posts() ) :, ie. the opening condition of the loop.


    Then reference the counter value inside the appropriate html.

    <div class="someclass-<?php echo $your_counter; ?>">

    If you want the counter to start at zero instead of one, simply move the increment, ie. $your_counter++; before the endwhile; instead.

  4. KhalidQ
    Posted 3 years ago #

    I realized I didn't post back, so here I am tying loose ends;

    Thanks you both for the direct replies! Yes the solution worked perfectly well, and Mark broke it down and explained nicely :)


Topic Closed

This topic has been closed to new replies.

About this Topic