Raging Vids
Raging Vids

Reputation: 121

Wordpress how to get the post thumbnail inside a figure tag

I am running a query loop and want that 'if' the post has a featured image, it needs to be inside a <figure> tag. But the featured image's <img> tag is appearing before the <figure> tag. What could be the reason?

        foreach($posts as $post){
            setup_postdata($post);
            

            echo '<article class="pet_post">';
                if(has_post_thumbnail()) { echo '<figure class="post_thumbnail">'. the_post_thumbnail('full') . '</figure>'; };
                echo '<h1 class="post_title">'. get_the_title() . '</h1>';
                echo '<p class="pet_seller">'. get_the_content() . '</p>';
                echo '<form method="POST">';
                    echo '<input type="hidden" name="post-id" value="'. get_the_ID() . '">';
                    echo '<button type="submit" name="delete-post">Delete this post</button>';
                echo '</form>';   
            echo '</article>';
        };

The problem can be better understood with this image: enter image description here

Upvotes: 0

Views: 1306

Answers (3)

Divjot Singh
Divjot Singh

Reputation: 26

You can also use the post_thumbnail_html filter hook to programmatically customize post thumbnail's <img> tag.

function my_theme_filter_post_thumbnail($html) {

    $html = "<figure>{$html}</figure>";
    return $html;
}
add_filter('post_thumbnail_html', 'my_theme_filter_post_thumbnail');

In the code above, the callback function for post_thumbnail_html hook accepts the <img> HTML tag as an argument.The argument is modified to add the <figure> tags around it.

I had blogged about it recently.

Upvotes: 1

Oscar Diaz
Oscar Diaz

Reputation: 11

I believe this approach is also acceptable.

<figure class="post_thumbnail">
    <?php if(has_post_thumbnail()) { echo the_post_thumbnail('full'); }; ?>
</figure>

Upvotes: 1

Ruvee
Ruvee

Reputation: 9097

It's because you're using the_post_thumbnail function which echo the image by default which happens sooner than echoing out the figure tag.

Replace

echo '<figure class="post_thumbnail">'. the_post_thumbnail('full') . '</figure>';

with

echo '<figure class="post_thumbnail"><img src="' . get_the_post_thumbnail_url(get_the_ID(), "full") . '"></figure>';

Upvotes: 2

Related Questions