WordPress.org

Ready to get started?Download WordPress

Forums

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

  1. KhalidQ
    Member
    Posted 1 year ago #

    Hello

    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">
    			<h1>
    				<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    			</h1>
    
    	<p>
    		<?php the_content(); ?> 
    
    		</div>
    	</div>
    
    	<section class="[LOOP HELP HERE]" data-speed="4" data-type="background">
          <h2>Image goes here</h2>
    </section>
    
    	<?php endwhile; else: endif; ?>

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

    Thanks!

  2. bcworkz
    Member
    Posted 1 year 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
    Moderator
    Posted 1 year 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.

    $your_counter++;

    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
    Member
    Posted 1 year 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 :)

    resolved.

Topic Closed

This topic has been closed to new replies.

About this Topic