Skip to content
Advertisement

PHP outputs images before divs – wordpress bootstrap carousel multiple items

I’m trying to create a wordpress slider with bootstrap carousel displaying multiple post on one slide. I have a problem with outputting the images in the <div class="col-xxl-4">.

This is my code:

<div class="header-slider">

  <div class="carousel slide carousel-fade" data-bs-ride="carousel">

    <div class="carousel-inner">
      <?php

        // Item size (set here the number of posts for each group)
        $i = 3;

        global $post;

        $args = array(
          'post_type' => 'slider',
          'posts_per_page' => -1,
          'orderby' => 'date',
          'order' => 'DESC',
        );

        $myposts = get_posts($args);

        if($myposts):

          $chunks = array_chunk($myposts, $i);
          $html = "";

          foreach($chunks as $chunk):

          ($chunk === reset($chunks)) ? $active = "active" : $active = "";
          $html .= '<div class="slider__slide carousel-item"><div class="row">';

          foreach($chunk as $post):

            $html .= '<div class="col-xxl-4">';
              $html .= the_post_thumbnail($post->ID);
            $html .= '</div>';

          endforeach;

          $html .= '</div></div>';

        endforeach;

        echo $html;

       endif;
      ?>
    </div><!-- .carousel-inner -->
  </div><!-- .carousel -->


</div><!-- .header-slider -->

and this the output I get: enter image description here

how can I fix this to get: <div class="col-xxl-4"><img src="..."></div>

Advertisement

Answer

Solution: Replace the_post_thumbnail by get_the_post_thumbnail.

When using call the_post_thumbnail, it will echo the content instantly, so you cannot use it to append to $html variable. You can check the the_post_thumbnail function is a wrapper of echo get_the_post_thumbnail.

function the_post_thumbnail( $size = 'post-thumbnail', $attr = '' ) {
    echo get_the_post_thumbnail( null, $size, $attr );
}

https://developer.wordpress.org/reference/functions/the_post_thumbnail/

And be cafully about the input parameter, I don’t see any parameter is $post->ID in the_post_thumbnail or get_the_post_thumbnail.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement