Chris Brosnan
Chris Brosnan

Reputation: 197

Show featured images of recent posts in Wordpress?

I have created a very simple plugin for my Wordpress site to display links to my most recent posts with the use of a shortcode ([recentposts]). The plugin works so far but I am struggling with finding a way to display the featured image for each post that is called in the <div> tags for each post link.

Can you please advise how I may do this. The code for my plugin is as follows:

<?php
/*
Plugin Name: Blog Display Blocks
Description: Plugin to display blog posts in block with shortcode
Author: Chris Brosnan
*/

function RecentPosts() {
    $recent_posts = wp_get_recent_posts(6);
    echo '<div class="blog-contain">';
    foreach( $recent_posts as $recent ){
        echo '<div class="third-box"><a href="' . get_permalink($recent["ID"]) . '">' .   $recent["post_title"].'</a> </div> ';
    } 
};

echo '</div>';
add_shortcode('recentposts', 'RecentPosts');

register_activation_hook( __FILE__, array( 'Blogdisplay', 'plugin_activation' ) );
register_deactivation_hook( __FILE__, array( 'Blogdisplay', 'plugin_deactivation' ) );

?>

What would I need to do in order to show the featured image alongside the corresponding link for each post that is called?

Upvotes: 2

Views: 1671

Answers (2)

PHPExpert
PHPExpert

Reputation: 943

Within your code by using wp_get_recent_posts() you will get the post id($recent["ID"]), then you can use any one of following, just add this in your code where you want to show the featured image.

$image = wp_get_attachment_image_src( get_post_thumbnail_id( $recent["ID"] ), 'single-post-thumbnail' );
or can use
echo get_the_post_thumbnail($recent["ID"], 'featured-image');

Upvotes: 0

Chris Brosnan
Chris Brosnan

Reputation: 197

Through trial and error combined with some further searching I have now found the solution to my question.

<?php
/*
Plugin Name: Blog Display Blocks
Description: Plugin to display blog posts in block with shortcode
Author: Chris Brosnan
*/

add_image_size( 'featured-thumb', 300, 200, true ); // (cropped)
function RecentPosts() {
    $rPosts = new WP_Query();
    $rPosts->query('showposts=6');
        while ($rPosts->have_posts()) : $rPosts->the_post(); ?>
        <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'featured-thumb' ); ?>
        <?php $image_url = $image[0]; ?>
            <a href="<?php the_permalink(); ?>">
            <div class="third-box" style="background-image: url(<?php echo $image_url; ?>);">
                <p><?php the_title();?></p>
            </div>
            </a>
        <?php endwhile;
    wp_reset_query();
};
add_shortcode('recentposts', 'RecentPosts');

register_activation_hook( __FILE__, array( 'Blogdisplay', 'plugin_activation' ) );
register_deactivation_hook( __FILE__, array( 'Blogdisplay', 'plugin_deactivation' ) );

?>

Upvotes: 1

Related Questions