I have a situation where only way seems to use loop inside a loop. Is that a good idea?

Like everybody else, Im looking for the most optimized solution possible.


  • I need to assing different markers for each type (these are taxonomies).
  • Yes, these markers are markers on Google Map API.
  • My code below is inside while loop that gets all posts I need.
  • URL from code is then used in Google Map JS to assing marker image.

What I've got:

// Types   
$car_type = get_the_terms( $post->ID, 'car-type' );

foreach ( $car_type as $type ) { 

    $type_slug = $type->slug;

    foreach ( $type_slug as $type_slug ) {
        $marker_image = 'https://www.my-site.com/media/markers/marker_' . $type_slug  . '.png';   

1 Answer 1


Your 2nd foreach loop is a bug. $slug is a string with a single value, and you cannot pass a string to a foreach loop. If you set debug to true, you will see an error message telling you just this.

You can simply just do

//Different markers for different types    
$car_type = get_the_terms( $post->ID, 'car-type' );

//Apparently it don't get the slug if it's not in foreach loop 
foreach ( $car_type as $type ) { 

    $slug = $type->slug;
    $marker_image = 'https://www.my-site.com/media/markers/marker_' . $slug . '.png';  
  • Thanks! If works perfectly. Im not that good with loops yet & Im having trouble to fully understand them. Do I need to use break; somewhere too?
    – N00b
    Commented Sep 27, 2015 at 19:28
  • You do not need to break;, except if you only need the first result. You can do the same exact thing for another taxonomy term. I'm off to bed now, if you do run into an issue, feel free to start a new question:-) Commented Sep 27, 2015 at 19:39

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.