Its simple and answered quite often: I want to get the post thumbnail variable. Even if there is a lot of input, I could not make it work for me.
Here is my current code I use somewhere inside my front_page.php
template:
<?php
$args = array( 'numberposts' => '2' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<div class="post">';
echo '<div class="post_thumb" style="background-image:url('.get_the_post_thumbnail( $recent['ID'], 'thumbnail').')"></div>';
echo '<div class="content"';
echo '<h2 class="post_title">';
echo '<a href="'.get_permalink($recent["ID"]).'" title="'.$recent["post_title"].'" >'.$recent["post_title"].'</a>';
echo '</h2>';
echo '<p class="post_excerpt">'.$recent["post_excerpt"].'</p>';
echo '</div>'; //content
echo '</div>'; //.post
}
?>
This works quite good, except for the get_the_post_thumbnail()
part.
I know, that I can get the thumbnail url using
$post_thumbnail_id = get_post_thumbnail_id($post->ID);
$post_thumbnail_url = wp_get_attachment_url( $post_thumbnail_id );
But I am not able to implement this code inside of my own. I tried to add it inside foreach
and although before, but both does not seem to work. I do not receive any errors I could look for, it only outputs "nothing", meaning there is no style="background-image: url()";
.
I would love if there is someone that could not only show, but explain, why my code is not working. I guess, that if I have solved this problem, my next question would be *where do I have to add 'thumbnail'
in order to output the correct image size?
Broken code
<?php
$args = array( 'numberposts' => '2' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
$post_thumbnail_id = get_post_thumbnail_id($post->ID);
$post_thumbnail_url = wp_get_attachment_url( $post_thumbnail_id );
echo '<div class="post">';
echo '<div class="post_thumb" style="background-image:url('.$post_thumbnail_url.')"></div>';
echo '<div class="content"';
echo '<h2 class="post_title">';
echo '<a href="'.get_permalink($recent["ID"]).'" title="'.$recent["post_title"].'" >'.$recent["post_title"].'</a>';
echo '</h2>';
echo '<p class="post_excerpt">'.$recent["post_excerpt"].'</p>';
echo '</div>'; //content
echo '</div>'; //.post
}
?>
<div class="post_thumb" style="background-image:url('.$post_thumbnail_url.')"></div>
if you check through inspect element ?$post_thumbnail_id = get_post_thumbnail_id($post->ID);
this line, you have used$post->ID
. I believe that is not used in actual code, because you are usingforeach
loop.