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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ha thanks! yes I was complicating things with the variable variables. I will upvote when I get more rep.
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.

1 Comment

Thank you Dan Dinu, will upvote when I get more rep for sure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.