How to loop over custom fields in a page template?

Try this to loop through up to 4 slides – checking each for a valid slide:

<?php
    $max_slides = 4; // this should be the maximum number of slides there can be

    for ($i=1; $i<=$max_slides; $i++) { 
        // check for slide
        $key = 'slide' . $i; 
        $slide = get_post_meta($post->ID, $key, $single = true);
        // check for slide text
        $thumb_text = get_post_meta($post->ID, $key . '_label', $single = true);
        // if there's a slide
        if($slide !== '') { ?>
            <section class="carousel slide" data-ride="carousel">
                <div class="carousel-inner">
                    <div class="item active">
                        <img src="https://wordpress.stackexchange.com/questions/207595/<?php echo $slide; ?>" class="slider-images" />
                    </div>
                    <div class="carousel-caption">
                        <h2><?php if($slide_text !== '') { echo $slide_text; } else { echo the_title(); } ?></h2>
                    </div>
                </div>
            </section>
        <?php } // end if statement
    } 
?>

You can change $max_slides to go through more than 4

Leave a Comment