I have a single page for my products where all products get listed. This is how i've archieved it:

<ul class="produkte">
    <?php $args = array( 'post_type' => 'produkte', 'posts_per_page' => 30 );

    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
        echo '<li class="produkt">';
        echo '<a href="' . get_permalink() . '">';
        echo '<div class="produkt-info">';
        the_title('<h3>', '</h3>');
        if (has_post_thumbnail()) {
            echo '<figure class="imgBox">';
           the_post_thumbnail('full', array('class' => 'img-resp') );
           echo "</figure>";
        echo '</div>';
        echo '</a>';
        echo '</li>';
    endwhile; ?>

I decided that i want to set the post thumbnail as the background-image of the li.produkt. When i do something like this:

echo '<li class="produkt" style="background: url('.the_post_thumbnail().')">';

The page generates an image-element above the li-element. What am i doing wrong??


The problem here is the_post_thumbnail() doesn't return image url but the img tag.

You can use this code

$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
echo '<li class="produkt" style="background: url('. $url.')">';
| improve this answer | |

There is now the get_the_post_thumbnail_url function provided in WordPress.

Usage example from the codex:

$featured_img_url = get_the_post_thumbnail_url(get_the_ID(),'full');


| improve this answer | |

Per WordPress Codex the the_post_thumbnail() function Display the post thumbnail. https://developer.wordpress.org/reference/functions/the_post_thumbnail/ But this output the whole image tag and not just the src, which in your case is needed.

Instead you should use the wp_get_attachment_image_src() function which Retrieve an image to represent an attachment.. https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/

So i suggest to try something like this:

//this retrieve the full version of image
$image_data = wp_get_attachment_image_src ( get_the_post_thumbnail( $post->ID), 'full' );
$image_url = $image_data[0];
echo '<li class="produkt" style="background: url('. $image_url .')">';
| improve this answer | |
  • Just pay attention that you have a bracket ")" more at the end of your first row. – Simone Cabrino Mar 29 '17 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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