skip to Main Content

As I am using a increment in PHP which output the number (1-unlimited) to div class ->

First of all let’s see the code:

  <?php $i = 0; ?>
        <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
    
    <div class="1-<?php echo ++$i ?>">
<h1 class="text">Demo</h1>
</div>
    
    <?php endwhile;

So i want to add a class to h1 or to div (like div class= 1-2 late) if div class is = 1-2 means how to add a class to h1 if increment number is two (2)

I expects

<div class="1-1">
    <h1 class="text">Demo</h1>
</div>
<div class="1-2">
    <h1 class="text class-here">Demo</h1>
</div><div class="1-3">
    <h1 class="text">Demo</h1>
</div>

2

Answers


  1. EDIT after OP’s clarification

    To only output the class if its the second loop you need an if statement

    <?php $i = 0; ?>
    <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
    <?php $i++; // increment i by one ?>
    <div class="1-<?php echo $i ?>">
        <h1 class="text <?php echo(($i = 2) ? ' some-class' : '') ?>">Demo</h1>
    </div>
    

    AGAIN: do not start your classes with a number. Start them with a letter.

    ALSO: if you only want to add different styles to the second loop-items h1 you can simply use css for that. Give the wrapping div for all loop items a class like i.e. "article", then do this

    .article:nth-child(2) h1 {
        /* your styles */
    }
    

    OLD ANSWER

    Not sure if I get your question right but why don’t you simply increment $i and then use it:

      <?php $i = 0; ?>
      <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
        <?php $i++; // increment i by one ?>
        <div class="1-<?php echo $i ?>">
            <h1 class="1-<?php echo $i ?> text">Demo</h1>
        </div>
    
    <?php endwhile;>
    

    Also if your wrapping div already has a class, you could simply access the h1 like this

    .32 1-2 h1
    

    CSS identifiers should not start with a number, this can lead to trouble (which is why I am escaping it above). It’s better to add a letter in front of the classname like

    .wrapper-1-2
    
    Login or Signup to reply.
  2. Use this code:

    <div class="1-<?= ++$i === 2 ? $i . ' class-here' : $i ?>">
        <h1 class="text">Demo</h1>
    </div>
    

    If $i equals 2 then it will add $i as class as well as your extra class. If not, it will only add $i as class.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search