0

I am trying to create a blog-listing page, that'll display the title and the featured images. Here's the loop that I am using

page.php

<div class="p-5 container" style="text-align:center;">
    <h1 style="margin-bottom:5vh;font-weight:bold;">Latest Posts</h1>
    <section class="thumbnails row">
    <?php $wpdb = new WP_Query(array(
            'post_type'=>'post',
            // 'post_type'       => 'publish',
            'post_status' => 'any',
            'posts_per_page' => 10));

            if($wpdb->have_posts()):
                while($wpdb->have_posts()):
                    $wpdb->the_post();?>
            <?php
            get_template_part('blog-show');
                // echo the_title();
                endwhile;
            endif;
            ?>
    </section>
</div>

blog-show.php

<div class="col-12 col-sm-4">
    <a href="<?php echo the_permalink() ?>">
        <img src="<?php the_post_thumbnail(); ?>"
             alt="<?php the_post_thumbnail_caption() ?>"/>
        <h3><?php the_title(); ?></h3>
    </a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</div>

I am able to use the the_post_thumbnail in another page but it doesn't work here.

1 Answer 1

0

the_post_thumbnail displays the post thumbnail. It generates HTML tag and echoes it. It does not echo only the URL to that image.

So this line:

<img src="<?php the_post_thumbnail(); ?>"
         alt="<?php the_post_thumbnail_caption() ?>"/>

Generates something like this:

<img src="<img src="" ... />"
         alt="..."/>

So it's not a correct HTML.

I'd changed it to:

<div class="col-12 col-sm-4">
    <a href="<?php the_permalink(); ?>">
        <?php the_post_thumbnail( 'post-thumbnail', array( 'alt' => get_the_post_thumbnail_caption() ) ); ?>
        <h3><?php the_title(); ?></h3>
    </a>
</div>
2
  • I tried your solution, but it doesn't seem to work. I checked the HTML render inside the browser and the code doesn't have an img tag altogether. Commented Jan 2, 2019 at 8:40
  • If the_post_thumbnail doesn't display any image, then there is something wrong with the thumbnail itself. Do you use native thumbnails? Commented Jan 2, 2019 at 8:41

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.