1

I thought of a while loop but cant find the way around this:

$foo1 = get_post_meta( $post->ID, '_item1', true );
if (!empty($foo1)){
    echo  ("<div class='$foo1'></div>"); 
}

$foo2 = get_post_meta( $post->ID, '_item2', true );
if (!empty($foo2)){
    echo  ("<div class='$foo2'></div>"); 
}

And so on... for a hundred times until I reach $foo100 and _item100 Any idea to achieve this to not repeat these 4 lines over and over?

Seolead
  • 13
  • 3

2 Answers2

2

You don't need variable variables for that, but just a for loop like this:

for( $i=1; $i<101; $i++ ) {
  $klass = get_post_meta( $post->ID, '_item' . $i, true );
  if( !empty($klass) ) {
     echo "<div class='$klass'></div>"; 
  }
}

This works as long as you do not need the $fooX variables later on. If you need them, you would have to use either mentioned variable variables or an array to collect all the values.

Sirko
  • 72,589
  • 19
  • 149
  • 183
  • Ha thanks! yes I was complicating things with the variable variables. I will upvote when I get more rep. – Seolead Jun 04 '13 at 06:17
1

you're thinking well at a while loop

You could use:

   $counter = 1;
   while ($counter< 100) // or whatever limit you have
   {
       $foo = get_post_meta( $post->ID, '_item' . $counter , true );
         if (!empty($foo)){
           echo  ("<div class='$foo' . $counter .' ></div>"); 
              }
     $counter++;
    } 

If you copy this code you're probably get into some compiling errors because of the string concatenation.

Basically you need to concatenate "_item" string with your current $counter.

Here are some string concatenation examples.

Let me know if you have any questions.

Goose
  • 4,764
  • 5
  • 45
  • 84
Dan Dinu
  • 32,492
  • 24
  • 78
  • 114